From my observation from Gmail and TED app the behavior of up navigation it will navigate to parent with the same state (scroll position) not like what Google say in their doc Implement Up Navigation which like create a parent intent and start it.
I implement the code from Android sample code and all state are gone (All Extra parameters I have previously set and scroll position). What is the proper way on this ? I can't find any on Android document.
Below is the code:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = new Intent(this, MyParentActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
.addNextIntent(new Intent(this, MyGreatGrandParentActivity.class))
.addNextIntent(new Intent(this, MyGrandParentActivity.class))
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
In my case I got 3 activities say A B and C, when user navigate from A to B I put some extras and onCreate
of B I use that extras to query data from database to populate my rows and when I navigate back from C all extras are gone and Activity B show nothing.
This is an alternative solution to the accepted answer:
If you cannot change the launchMode
of your activity or if the parent activity is not on top of the back stack (e.g. A is parent of C), you cannot use the solution above. In this case you have to extend your navigateUpTo
call to tell the activity, that it should not be recreated, if it is on the back stack:
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
NavUtils.navigateUpTo(this, intent);
I had a similar issue when I called startActivityForResult() in my main activity with fragments and then tried to return to it from the callee using Up navigation. Solved by implementing Up navigation as:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
setResult(RESULT_CANCELED);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
In this case Up button behaves like an ordinary Back button and all states are preserved.
you can use this :
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With