From a910d80663ce38ab125223ee9e51512e4ebbe888 Mon Sep 17 00:00:00 2001 From: Murray Cumming Date: Thu, 8 Jan 2015 09:22:47 +0100 Subject: [PATCH] ExampleViewerActivity: Make the Toolbar's Up Button go back properly. Override onOptionsItemSelected() so we can modify the Intent used with navigateUpTo(), to specify FLAG_ACTVITY_CLEAR, so we resume the parent activity instead of recreating it, just as if the user had used the back button - which the user generally cannot distinguish from the up button anyway. We could instead have marked the parent activity as singleTop in the manifest, but it seems nice to keep this parent activity more flexible. This should fix this bug: https://github.com/murraycu/android-galaxyzoo/issues/14 --- .../galaxyzoo/app/ExampleViewerActivity.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/app/src/main/java/com/murrayc/galaxyzoo/app/ExampleViewerActivity.java b/app/src/main/java/com/murrayc/galaxyzoo/app/ExampleViewerActivity.java index 2bc0fae8..707c0c4d 100644 --- a/app/src/main/java/com/murrayc/galaxyzoo/app/ExampleViewerActivity.java +++ b/app/src/main/java/com/murrayc/galaxyzoo/app/ExampleViewerActivity.java @@ -22,6 +22,8 @@ import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; +import android.support.v4.app.NavUtils; +import android.view.MenuItem; public class ExampleViewerActivity extends BaseActivity { @@ -65,4 +67,33 @@ protected void onCreate(final Bundle savedInstanceState) { showUpButton(); } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + // Handle presses on the action bar items + final int id = item.getItemId(); + + if (id == android.R.id.home) { + //The base class just uses NavUtils.navigateUpFromSameTask() but we want to make sure + //that the parent activity will be resumed instead of restarted, + //to make sure we go back to the correct help for the correct question, + //so we use FLAG_ACTIVITY_CLEAR_TOP. + //Alternatively, we could just mark QuestionHelpActivity as + //android:launchMode="singleTop" in the AndroidManifest.xml but it seems reasonable to + //use QuestionHelpActivity from other places one day. + + //We can use this instead of more complex code, checking NavUtils.shouldUpRecreateTask(), + //because we know that our activities will never be opened from another app. + //See http://developer.android.com/training/implementing-navigation/ancestral.html. + final Intent upIntent = NavUtils.getParentActivityIntent(this); + if (upIntent != null) { + upIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + } + + NavUtils.navigateUpTo(this, upIntent); + return true; + } + + return super.onOptionsItemSelected(item); + } }