How to start new activity on button click

后端 未结 24 1712
傲寒
傲寒 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:43

    Starting an activity from another activity is very common scenario among android applications.
    To start an activity you need an Intent object.

    How to create Intent Objects?

    An intent object takes two parameter in its constructor

    1. Context
    2. Name of the activity to be started. (or full package name)

    Example:

    So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).

    Here is the code snippet which shows how to start DetailActivity from

    HomeActivity.

    Intent i = new Intent(HomeActivity.this,DetailActivity.class);
    startActivity(i);
    

    And you are done.

    Coming back to button click part.

    Button button = (Button) findViewById(R.id.someid);
    
    button.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View view) {
             Intent i = new Intent(HomeActivity.this,DetailActivity.class);
             startActivity(i);  
          }
    
    });
    

提交回复
热议问题