问题
I'm developing some application and I have one problem.
I have : 1. Activity A (Navigation Drawer pattern) with ListFragment in FrameLayout: xml:
<FrameLayout
...>
</FrameLayout>
<LinearLayout
...>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
- Activity B which shows the detail data of ListView in ListFragment.
How can I go back (using Navigation Up Button) from activity B to Activity A with saving UI of the ListFragment (Activity re-creates if I go back using Home Back). Btw, if I press the back button on my phone, activity does not re-create and returns in previous state.
回答1:
When you use UP navigation, then the previous activity is recreated. To prevent that from happening while you preserve the UP navigation, you can get the intent of the parent activity, and bring it to front if it exists, otherwise create it if not.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent parentIntent = NavUtils.getParentActivityIntent(this);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(parentIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
I also specified launchMode="singleTop"
in the Manifest. but I am not sure if that was necessary.
回答2:
One thing you can do to prevent the first activity to recreate is by just calling finish()
on the second activity when that back button is pressed.
Not tested, but I believe the id is android.R.id.home
, so all you have to do is override onOptionsItemSelected
in the second activity, like this:
/**
* Handles the selection of a MenuItem.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
来源:https://stackoverflow.com/questions/30059474/android-navigation-up-from-activity-to-fragment