java – setDisplayHomeAsUpEnabled not working in one of my Activities but everywhere else it does work-ThrowExceptions

Exception or error:

For some reason this doesn’t work in one of my activities but everywhere else it works fine when i press the back arrow in the toolbar it goes back to my MainActivity.

import androidx.appcompat.widget.Toolbar;

//Initializing toolbar
mToolbar = findViewById(R.id.mToolbar);
setSupportActionBar(mToolbar);

if((getSupportActionBar() != null)){
    getSupportActionBar().setTitle(R.string.equalizerTitle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home_up);
}

Manifest

<activity
     android:name=".activities.EqualizerActivity"
     android:parentActivityName=".activities.MainActivity"
     android:screenOrientation="portrait"/>

EDIT

This activity uses a constraint layout as parent but i don’t see why this would be the cause, all other activities use RelativeLayout and there they work fine.

How to solve:

Looks like you are using onOptionsItemSelected() method to handle menu buttons. The issue is that the “back” button is also kind of a menu button.

In order for Android to know that you don’t have a specific handler for the button and it should be handled by the framework, you need to let Android know it via returning false when you don’t “consume” the event. According to the docs:

onOptionsItemSelected()

boolean Return false to allow normal menu processing to proceed, true to consume it here.

So, you should have smth like this:

public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
               case YOUR_BUTTON:
                   // do something
                   return true;
       }
       // By default, allow Android to work on it
       return false;

Leave a Reply

Your email address will not be published. Required fields are marked *