导航抽屉汉堡包图标在手动滑动抽屉之前不会显示

时间:2015-12-15 18:28:09

标签: android android-layout navigation-drawer

我做了一些搜索并尝试了很多解决方案,但我会遇到同样的问题:

在我刷抽屉之前,抽屉汉堡包图标不显示。

enter image description here

这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    setSupportActionBar(toolbar);
    setupDrawer();
    ...
}

//calling the method bellow inside onCreate
public void setupDrawer(){
    mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            syncState();
        }
    };

    mDrawerToggle.setDrawerIndicatorEnabled(true);
    drawerLayout.setDrawerListener(mDrawerToggle);
    ActionBar actionBar =  getActionBar();

    if(actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.drawable.ic_launcher);
    }
}

我希望它显示出来。

3 个答案:

答案 0 :(得分:3)

尝试通过 getSupportActionBar()方法获取操作栏,而不是 getActionBar()。在 setupDrawer()方法内:

mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
// here
//ActionBar actionBar =  getActionBar();
ActionBar actionBar =  getSupportActionBar();

答案 1 :(得分:1)

当您使用Toolbar,可能还有ActionBarActivity时,您没有内置ActionBarActionBarActivity提供了Toolbar公开常见ActionBar方法(如setDisplayShowHomeEnabled(boolean enabled))的包装器。但是要获得此包装器,您必须调用getSupportActionBar()而不是getActionBar()

在您的代码中,它只是转换为:

public void setupDrawer(){
    // ...

    mDrawerToggle.setDrawerIndicatorEnabled(true);
    drawerLayout.setDrawerListener(mDrawerToggle);
    ActionBar actionBar =  getSupportActionBar();

    if(actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.drawable.ic_launcher);
    }
}

答案 2 :(得分:0)

从@BahodirovMirjalol解决方案修复后:

mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
ActionBar actionBar =  getSupportActionBar();

我遇到了另一个问题,因为导航后退图标显示而不是hamburguer ,所以我在onCreate方法之上添加了这两个方法并且它可以工作:

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

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
}

找到here