人有我精的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