Clicking hamburger icon on Toolbar does not open Navigation Drawer

后端 未结 13 2883
太阳男子
太阳男子 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:36

    You need to sync the drawer toggle:

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }
    

    EDIT: That code is working for me (copied from your post)

    public class TempActivity extends AppCompatActivity {
        private ActionBarDrawerToggle mDrawerToggle;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.temp);
            setupDrawer();
        }
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            mDrawerToggle.onConfigurationChanged(newConfig);
        }
        @Override
        public boolean onOptionsItemSelected(final MenuItem item) {
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            mDrawerToggle.syncState();
        }
        private void setupDrawer() {
            Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.my_drawer_layout);
            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close) {
                public void onDrawerClosed(View view) {
                    super.onDrawerClosed(view);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                }
                public void onDrawerOpened(View drawerView) {
                    super.onDrawerOpened(drawerView);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                }
            };
            mDrawerLayout.setDrawerListener(mDrawerToggle);
        }
    }
    
    
        
            
            
        
        
            
        
    
    

    But if you are using the new NavigationView, then you don't need the toggle etc. Here is a good example how to use it.

提交回复
热议问题