Cannot catch toolbar home button click event Cannot catch toolbar home button click event android android

Cannot catch toolbar home button click event


If you want to know when home is clicked is an AppCompatActivity then you should try it like this:

First tell Android you want to use your Toolbar as your ActionBar:

setSupportActionBar(toolbar);

Then set Home to be displayed via setDisplayShowHomeEnabled like this:

getSupportActionBar().setDisplayShowHomeEnabled(true);

Finally listen for click events on android.R.id.home like usual:

@Overridepublic boolean onOptionsItemSelected(MenuItem menuItem) {    if (menuItem.getItemId() == android.R.id.home) {        Timber.d("Home pressed");    }    return super.onOptionsItemSelected(menuItem);}

If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));toolbar.setNavigationOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        Log.d("cek", "home selected");    }});

If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.


    mActionBarDrawerToggle = mNavigationDrawerFragment.getActionBarDrawerToggle();    mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            // event when click home button        }    });

in mycase this code work perfect


This is how I do it to return to the right fragment otherwise if you have several fragments on the same level it would return to the first one if you donĀ“t override the toolbar back button behavior.

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