How to start new activity on button click

后端 未结 24 1662
傲寒
傲寒 2020-11-21 05:54

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

相关标签:
24条回答
  • 2020-11-21 06:33

    An old question but if the goal is to switch displayed pages, I just have one activity and call setContentView() when I want to switch pages (usually in response to user clicking on a button). This allows me to simply call from one page's contents to another. No Intent insanity of extras parcels bundles and whatever trying to pass data back and forth.

    I make a bunch of pages in res/layout as usual but don't make an activity for each. Just use setContentView() to switch them as needed.

    So my one-and-only onCreate() has:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        LayoutInflater layoutInflater = getLayoutInflater();
    
        final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
        setContentView (mainPage);
        Button openMenuButton = findViewById(R.id.openMenuButton);
    
        final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
        Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
    
        openMenuButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setContentView(menuPage);
            }
        });
    
        someMenuButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                do-something-interesting;
                setContentView(mainPage);
            }
        }
    }
    

    If you want the Back button to go back through your internal pages before exiting the app, just wrap setContentView() to save pages in a little Stack of pages, and pop those pages in onBackPressed() handler.

    0 讨论(0)
  • 2020-11-21 06:34

    Write the code in your first activity .

    button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
    
    
    Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
                           //You can use String ,arraylist ,integer ,float and all data type.
                           intent.putExtra("Key","value");
                           startActivity(intent);
                            finish();
                }
             });
    

    In secondActivity.class

    String name = getIntent().getStringExtra("Key");
    
    0 讨论(0)
  • 2020-11-21 06:36

    Kotlin

    First Activity

    startActivity(Intent(this, SecondActivity::class.java)
      .putExtra("key", "value"))
    

    Second Activity

    val value = getIntent().getStringExtra("key")
    

    Suggestion

    Always put keys in constant file for more managed way.

    companion object {
        val PUT_EXTRA_USER = "user"
    }
    startActivity(Intent(this, SecondActivity::class.java)
      .putExtra(PUT_EXTRA_USER, "value"))
    
    0 讨论(0)
  • 2020-11-21 06:37

    Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.

    1. Using the onClick attribute of the Button. (Beginner)
    2. Assigning an OnClickListener() via an anonymous class. (Intermediate)
    3. Activity wide interface method using the switch statement. (Pro)

    Here's the link to my example if you want to follow along:

    1. Using the onClick attribute of the Button. (Beginner)

    Buttons have an onClick attribute that is found within the .xml file:

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToAnActivity"
        android:text="to an activity" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="goToAnotherActivity"
        android:text="to another activity" />
    

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    }
    
    public void goToAnActivity(View view) {
        Intent intent = new Intent(this, AnActivity.class);
        startActivity(intent);
    }
    
    public void goToAnotherActivity(View view) {
        Intent intent = new Intent(this, AnotherActivity.class);
        startActivity(intent);
    }
    

    Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent.

    Disadvantage: Difficult readability when reviewing.

    2. Assigning an OnClickListener() via an anonymous class. (Intermediate)

    This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
    
            Button button1 = (Button) findViewById(R.id.button1);
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), AnActivity.class);
                    view.getContext().startActivity(intent);}
                });
    
            Button button2 = (Button) findViewById(R.id.button2);
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), AnotherActivity.class);
                    view.getContext().startActivity(intent);}
                });
    

    Advantage: Easy to make on the fly.

    Disadvantage: There will be a lot of anonymous classes which will make readability difficult when reviewing.

    3. Activity wide interface method using the switch statement. (Pro)

    This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.

    In Java class:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
    
        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button1:
                Intent intent1 = new Intent(this, AnActivity.class);
                startActivity(intent1);
                break;
            case R.id.button2:
                Intent intent2 = new Intent(this, AnotherActivity.class);
                startActivity(intent2);
                break;
            default:
                break;
        }
    

    Advantage: Easy button management because all button intents are registered in a single onClick() method


    For the second part of the question, passing data, please see How do I pass data between Activities in Android application?

    0 讨论(0)
  • 2020-11-21 06:38

    Emmanuel,

    I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

    Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
    
    myIntent.putExtra("key", value);
    
    CurrentActivity.this.startActivity(myIntent);
    
    0 讨论(0)
  • 2020-11-21 06:38

    From the sending Activity try the following code

       //EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
        public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           ....
    
            //Here we declare our send button
            Button sendButton = (Button) findViewById(R.id.send_button);
            sendButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //declare our intent object which takes two parameters, the context and the new activity name
    
                    // the name of the receiving activity is declared in the Intent Constructor
                    Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
    
                    String sendMessage = "hello world"
                    //put the text inside the intent and send it to another Activity
                    intent.putExtra(EXTRA_MESSAGE, sendMessage);
                    //start the activity
                    startActivity(intent);
    
                }
    

    From the receiving Activity try the following code:

       protected void onCreate(Bundle savedInstanceState) {
     //use the getIntent()method to receive the data from another activity
     Intent intent = getIntent();
    
    //extract the string, with the getStringExtra method
    String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
    

    Then just add the following code to the AndroidManifest.xml file

      android:name="packagename.NameOfTheReceivingActivity"
      android:label="Title of the Activity"
      android:parentActivityName="packagename.NameOfSendingActivity"
    
    0 讨论(0)
提交回复
热议问题