Skip to content

Commit

Permalink
ExampleViewerActivity: Make the Toolbar's Up Button go back properly.
Browse files Browse the repository at this point in the history
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:
#14
  • Loading branch information
murraycu committed Jan 8, 2015
1 parent 657b885 commit a910d80
Showing 1 changed file with 31 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}
}

0 comments on commit a910d80

Please sign in to comment.