How to get rid of back button in Android app bar

Viewed 118

I have a simple activity with several fragments that the user can switch between. Only when the first fragment is shown, a back button appears in the app bar.

This is the evil back button

I already tried to remove the back button in code by adding this to my activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
    }

    return super.onCreateOptionsMenu(menu);
}

But this does not work correctly: initially the back button is actually gone (yay!). But once I change to another fragment and then go back to the first one, the back button is there again.

Where does this back button come from? How can I disable it for good?

2 Answers

review the xml file would you add a toolbar there and try

setSupportActionBar()=null;

You are advised to use the Android toolbar to replace the Actionbar.
1. Go to the Android Manifest file and find the theme to be used.
Generally, the default value is android:theme="@style/AppTheme". You only need to change the first line to Theme.AppCompat.Light.NoActionBar.
2. Write the toolbar control to the layout file.

    <android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="@+id/toolbar"
android:background="@color/colorPrimary"
app:title="bar"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>

3. In the java file
Bind the toolbar and invoke the setSupportActionBar() method to set the current menu bar to the bound toolbar object.
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
If you want to use the return button, add the returned listener finish:

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
Related