Android Activities UI Persistence
I need to have two activities in an Android app that can be switched between each other with UI persistence as follows:
Activity A launches Activity B.
User triggers some UI changes in Activity B.
Activity B ret开发者_如何转开发urns to Activity A (by a call to
onBackPressed()
or something similar)Activity A re-launches Activity B.
I would like the changes made in step 2 to be visible in step 4.
I have tried using the singleInstance
activity tag on Activity B to no avail. I would also prefer a more elegant solution than simply writing all object properties to a file or SQLite table.
It seems that this behaviour must be easily achievable given that Android does it automatically for calls to onBackPressed()
where the parent Activity's UI is saved.
Any help is much appreciated.
Activity A launches Activity B
.
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivityForResult(intent);
Launch Activity B from Activity A using startActivityForResult.
User triggers some UI changes in Activity B
.
Activity B returns to Activity A (by a call to onBackPressed() or something similar)
Intent intent = new Intent();
intent.putExtra("change_value1", change1);
intent.putExtra("change_value2", change2);
setResult(RESULT_OK, intent);
finish();
Activity A re-launches Activity B.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/*
* Gets invoked on finish() from ActivityB.class
*/
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case 0:
if(resultCode == RESULT_OK){
String change1, change2;
change1 = data.getStringExtra("change_value1");
change2 = data.getStringExtra("change_value2");
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
}
}
You can read more about intents here.
If you want to persist data between multiple activities it's best to create a subclass of Application and put your objects in there. Then each activity you spawn can get hold of the same objects.
http://developer.android.com/reference/android/app/Application.html
How to declare global variables in Android?
精彩评论