How to start new activity on button click

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

    Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).

    Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
    i.putExtra("PersonID", personID);
    startActivity(i);
    

    Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.

    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {
         personID = extras.getString("PersonID");
    }
    

    Now if you need to share data between two Activities, you can also have a Global Singleton.

    public class YourApplication extends Application 
    {     
         public SomeDataClass data = new SomeDataClass();
    }
    

    Then call it in any activity by:

    YourApplication appState = ((YourApplication)this.getApplication());
    appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic
    

提交回复
热议问题