Calling setDisplayHomeAsUpEnabled for fragments in ActionBarCompat

Raquib-ul Alam picture Raquib-ul Alam · Feb 2, 2014 · Viewed 11.4k times · Source

I am using ActionBarCompat. When I load a child fragment, I want the home button to work as the up button. So I called this from the child fragment:

((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

But still the home button is not being shown as the up button. I have also added logic for the id android.R.id.home in onOptionsItemSelected, but it still does not work. Any ideas how I can get it done?

Answer

rodrigo-silveira picture rodrigo-silveira · Jun 13, 2014

I've struggled with this for a couple of long days, and here's what I've found to work. I'm hoping there's a better solution, but this does get the job done:

In my main activity (the one launching the fragment), create the following public function, which will be called by the "child" fragment:

// The method is in MainActivity.java
public void resetActionBar(boolean childAction, int drawerMode)
{
    if (childAction) {
        // [Undocumented?] trick to get up button icon to show
        drawerToggle.setDrawerIndicatorEnabled(false);
        mActionBar.setDisplayHomeAsUpEnabled(true);
    } else {
        drawerToggle.setDrawerIndicatorEnabled(true);
    }

    drawerLayout.setDrawerLockMode(drawerMode);
}

Then, from your fragment that you want the Up button to appear, just call that method as follows (adapting class names as needed):

// This method in in SomeFragment.java
((MainActivity)getActivity()).resetActionBar(true,
      DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

To summarize, here's how to enable up button from fragment:

  • Disable the drawer indicator on the drawerToggle object -- call setDrawerIndicatorEnabled(false)
  • Set displayHomeAsUp -- call setDisplayHomeAsUpEnable(true) on actionBar object
  • Optionally, lock the drawer, so it won't appear on edge swipe

Hope this helps, and I'm hoping this becomes easier in the future...