Cannot catch toolbar home button click event

前端 未结 11 1994
悲&欢浪女
悲&欢浪女 2020-11-27 02:56

I\'ve implemented the newest appcompat library and using the Toolbar as action bar. But the problem is I cannot catch the home button / hamburger icon click eve

11条回答
  •  暖寄归人
    2020-11-27 03:15

    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:

    @Override
    public 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.

提交回复
热议问题