Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Toolbar Home / Back button programmatically in Android?

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://imgur.com/y5AgYde.jpg "tooltip"

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

like image 613
Andre Andriole Avatar asked Sep 17 '19 00:09

Andre Andriole


2 Answers

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.

like image 174
Gabriele Mariotti Avatar answered Sep 25 '22 23:09

Gabriele Mariotti


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);
    }
like image 21
Emad Seliem Avatar answered Sep 26 '22 23:09

Emad Seliem