Clicking hamburger icon on Toolbar does not open Navigation Drawer

后端 未结 13 2783
太阳男子
太阳男子 2020-12-14 00:08

I have a simple android.support.v7.widget.Toolbar and all I am trying to do is to open a NavigationDrawer by pressing the \"hamburger\" icon in the top left cor

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 00:22

    Use ActionBarDrawerToggle and implement public boolean onOptionsItemSelected(MenuItem item)

    Toolbar DOES NOT have to be within a DrawerLayout, it's not likely to be the cause of this issue. toggle.onOptionsItemSelected(item) looks for the ID of the item selected and if it is android.R.id.home then the drawer's visibility is toggled. Thus Toolbar, or any View that creates a Home MenuItem, can be placed anywhere in your layout.

    Within your activity:

    ActionBarDrawerToggle toggle;
    
    private void setupDrawerToggleInActionBar() {
        // assuming a Toolbar has been initialized in your onCreate
        this.setSupportActionBar(toolbar);
    
        // setup the action bar properties that give us a hamburger menu
        ActionBar actionBar = this.getSupportActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    
        // the toggle allows for the simplest of open/close handling
        toggle = new ActionBarDrawerToggle(this,
                                           drawerLayout,
                                           R.string.navigation_drawer_open,
                                           R.string.navigation_drawer_close);
        // drawerListener must be set before syncState is called
        drawerLayout.setDrawerListener(toggle);
    
        toggle.setDrawerIndicatorEnabled(true);
        toggle.syncState();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        // This is required to make the drawer toggle work
        if(toggle.onOptionsItemSelected(item)) {
            return true;
        }
    
        /*
         * if you have other menu items in your activity/toolbar 
         * handle them here and return true
         */
    
        return super.onOptionsItemSelected(item);
    }
    

提交回复
热议问题