Hide Toolbar Home / Back button programmatically in Android?
L

2

5

My app has an item selection just like WhatsApp and on long click I can select multiple items to delete them. Everything is working fine until I need a button to clear selection. I want to use the back button (arrow) to clear the selection and I want the back arrow to disappear after clicked but I couldn't find a way to do that.

supportActionBar?.setDisplayHomeAsUpEnabled(false)

This would be the first solution but I think it cant hide the button programmatically.

I tried doing this too because I do this with the bin icon to delete but it didn't work with the back arrow.

toolbarMainActivity.menu.findItem(R.id.home).isVisible = false

I also tried changing values in the toolbar, appbar layout and the menu_main.xml file but couldn't set gravity or force the icon to the position of the back arrow before the app title.

This works on app start but after setting it to true setting it to false doesn't hide the arrow, only recreating

supportActionBar?.setDisplayHomeAsUpEnabled(false)

![1]: https://i.sstatic.net/AGFJm.png "tooltip"

I just want to hide the back button after pressing it to clear selection.

Lithomarge answered 17/9, 2019 at 0:32 Comment(0)
S
8

If you're using a Toolbar you can use its own navigation icon API.

You can change the icon using:

toolbar.setNavigationIcon(R.drawable....);

In you case you can use:

toolbar.setNavigationIcon(null);

You can add add an OnClickListener

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //...Do something
      }
    });

You can use an androidx.appcompat.widget.Toolbar or can use a MaterialToolbar included in the Material Components library.

Shirr answered 17/9, 2019 at 7:19 Comment(2)
Thank you, it worked ! But now supportActionBar?.setDisplayHomeAsUpEnabled(true) doesn't make the button visible anymore. Where can I find the right drawable for navigation button ?Lithomarge
In the official material icons collection.Shirr
F
3

try this solution for showing back button

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

for hiding back button

if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(false);
    }
Furlana answered 17/9, 2019 at 5:28 Comment(1)
supportActionBar?.setDisplayHomeAsUpEnabled(false) This is just the same but getter method kotlin.Lithomarge

© 2022 - 2024 — McMap. All rights reserved.