Question

Can I make the action bar's "up" navigation trigger a confirmation dialogfragment that says "Are you sure you would like to go back?"

Was it helpful?

Solution

Intercepting the up ActionBar button press is trivial because everything is done through onOptionsItemSelected. The documentation, recommends that you use android.R.id.home to go up with NavUtils (provided that you set the metadata for the parent activity so NavUtils doesn't throw an Exception, etc):

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Your DialogFragment should offer an confirmation to actually go back. Since you're now working with the Fragment and not the Activity, you're going to want to pass getActivity() to NavUtils.

NavUtils.navigateUpFromSameTask(getActivity());

and change onOptionsItemSelected() to

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        new ConfirmationDialog().show(getSupportFragmentManager(), "confirmation_dialog");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

ConfirmationDialog is your custom DialogFragment.

Note that for this example, I am using the support Fragment APIs,. If you are not, make sure to change getSupportFragmentManager() to getFragmentManager().

OTHER TIPS

Yes. Pressing the "up" button just calls the option menu callback with R.id.home. So you could just grab that, display the dialog box and if the positive button is pressed call NavUtils.navigateUpTo().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top