Search code examples
androidandroid-fragmentsandroid-actionbarandroid-event

Android ActoinBar homeAsUp only works once


I'm working on an app that only uses a single Activity and switches out fragments as they are needed with the navigation drawer. Now we want to navigate back from one of these fragments by using the homeAsUp button in the ActionBar.

I have followed all the steps to set the button up. From disabling the navigation drawer setDrawerIndicatorEnabled(false) and calling setDisplayHomeAsUpEnabled(true) in the fragment's onCreateView(). I also set setHomeButtonEnabled(true) in the MainActivity's onCreate() however because the app is already in the MainActivity, we cannot specify a Parent Activity.

Whenever I run a fresh install of the app, the homeAsUp button works and is registered in the onBackPressed(), not onOptionsItemSelected() method. However, when I close the app and run it again the button does not even register clicks.

In onBackPressed() I check a few conditions, but it does not block the button press. In onOptionsItemSelected() I check for android.R.id.home.

Unfortunately, I cannot post the code.

This post describes what I'm trying to achieve: Switching between Android Navigation Drawer image and Up caret when using fragments


Solution

  • I managed to fix the issue I was experiencing. It was a very simple mistake. Because I'm not the original author of this code, I went through the MainActivity thoroughly. As it turns out the original author called setDisplayHomeAsUpEnabled in the onCreate function (which is extremely long), but near the end he also called setSupportActionBar, which made the first call of setDisplayHomeAsUpEnabled useless. Moving setDisplayHomeAsUpEnabled below setSupportActionBar fixed my problem.

    If you did everything correctly, make sure that your code is written in the correct order.

    Furthermore, if you use custom toolbars in other fragments, remember to set your original Support Action Bar by calling setSupportActionBar(toolbar.find(this)) in onResume of your MainActivity.