LorenzoBerti LorenzoBerti - 1 month ago 11
Android Question

Toolbar NavigationOnClick not work

Hello I have a problem with listen click on navigation icon on my toolbar:

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48dp);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Log.e("navigation", "navigation");
}
});


I wrote this, but not work, it doesn't listen click and it doesn't log nothing.

Answer

Try this code and it will work.

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Some Title");
    myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Log.e("navigation", "navigation"); 
        }
    });

I think the problem is with this line " myToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_48dp);"

Edit:Tested the above code in 6.0,5.1 and it is working as expected.