How to add “menu” indicator next to Action Bar's app icon?

前端 未结 3 1832
心在旅途
心在旅途 2020-12-05 14:08

At least Gmail and Youtube Android apps use a side menu (navigation drawer?) that opens by swiping, or by clicking the app icon (home button):

3条回答
  •  情深已故
    2020-12-05 14:44

    To create similar implementation / look in your application you should use ActionBarDrawerToggle and set your custom icon as indicator next to ActionBar home button. For example :

    import android.app.ActionBar;
    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.widget.DrawerLayout;
    
    private void setUpDrawerToggle(){
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    
        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                             /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
    
            @Override
            public void onDrawerOpened(View drawerView) {
                invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };
    
        // Defer code dependent on restoration of previous instance state.
        // NB: required for the drawer indicator to show up!
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });
    
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }
    

    Where R.drawable.ic_drawer is actually the icon to use as indicator. You can find it in Android Asset Studio; see Navigation Drawer Indicator.

    References

    1. ActionBarDrawerToggle
    2. Creating a Navigation Drawer

提交回复
热议问题