人有我精的Android Studio,它采用工具栏,v7.app.ActionBarDrawerToggle和NavigationView代替NavigationDrawerFragment(和布局/ fragment_navigation_drawer.xml)的抽屉式导航活动项目模板。箭头显示,而不是材料设计版本汉堡包图标。为什么onPostCreate中的syncState不工作?
根据Google's guidance和reference,我设置了ActionBarDrawerToggle。我做到了1)在onCreate中实例化,2)在onPostCreate中调用syncState,3)调用onConfigurationChanged和onOptionsItemSelected。
除了一件事情之外,它几乎完美地工作:汉堡包图标显示为箭头。
在StackOverFlow上可以找到类似的问题,特别是对于this question。但问题是关于如何使用旧的R.drawable.ic_drawer作为汉堡,而不是材料设计(5.0 Lollipop版本之前)。此外,这个问题没有答案,提问者评论说他没有提出任何解决方案就解决了问题。
过了一段时间,我意外发现了一个解决方案。它有点脏。它是在onCreate中调用syncState。因为看起来,出于某种原因,onPostCreate没有在我的应用程序中调用。实际上,这个肮脏的解决方案用于an answer to the other problem。
但the official reference说调用syncState在onPostCreate。为什么它不起作用?为什么我的应用程序不会调用onPostCreate?这应该是没有显示汉堡图标(而不是显示箭头)的主要原因。
下面是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
drawerLayout.setDrawerListener(drawerToggle);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
drawerToggle.syncState(); // calling this here is somewhat a dirty solution
}
@Override
public void onPostCreate(Bundle savedInstanceState,
PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
...
}
我有同样的问题,这解决了它。谢谢! – developer10
非常好,谢谢! – mizerablebr