android - open navigation drawer by clicking the app icon?

后端 未结 2 514
攒了一身酷
攒了一身酷 2021-02-07 14:31

I use a navigation drawer in my app (the type of navigation that you open by sliding from the left side of the screen). Now, usually you can also open it by tapping the app icon

相关标签:
2条回答
  • 2021-02-07 14:46

    Everything you need is described in the Navigation Drawer Guide from Google. Basically, you need to enable the "up" action on the ActionBar:

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    Then you need to bind it to a Toggle:

           mDrawerToggle = new ActionBarDrawerToggle(
                    this,                  /* host Activity */
                    mDrawerLayout,         /* DrawerLayout object */
                    R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                    R.string.drawer_open,  /* "open drawer" description */
                    R.string.drawer_close  /* "close drawer" description */
                    ) {
    
                /** Called when a drawer has settled in a completely closed state. */
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                }
    
                /** Called when a drawer has settled in a completely open state. */
                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle(mDrawerTitle);
                }
            };
    
            // Set the drawer toggle as the DrawerListener
            mDrawerLayout.setDrawerListener(mDrawerToggle);
    
    0 讨论(0)
  • 2021-02-07 14:47

    I ran into this issue also, assuming you already have an ActionBarDrawerToggle as @Kernald suggested, you need to add the following also to your Activity:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        // Handle your other action bar items...
    
        return super.onOptionsItemSelected(item);
    }
    

    This let's the toggle handle the icon button press on the ActionBar, causing the Drawer to slide out.

    0 讨论(0)
提交回复
热议问题