我正在使用新的NavigationView,試圖將其實現爲DrawerLayout,並且我想將當前選定的菜單項保存在NavigationView的菜單中。 我知道我可以保存/恢復所選項目「手動」通過保存/恢復我的實例狀態:在導航視圖上保存狀態
public class MyActivity extends AppCompatActivity {
private static String STATE_SELECTED_POSITION = "state_selected_position";
private int mCurrentSelectedPosition;
private NavigationView mNavigationView;
private FrameLayout mContentFrame;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mContentFrame = (FrameLayout) findViewById(R.id.content_frame);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch(menuItem.getItemId()) {
case R.id.navigation_item_1:
Snackbar.make(contentFrame, "Item One", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
return true;
case R.id.navigation_item_2:
Snackbar.make(contentFrame, "Item Two", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
return true;
default:
return false;
}
}
});
}
// Saving the currently selected menu item (index).
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
// Restoring selected menu item.
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
mNavigationView.getMenu().getItem(mCurrentSelectedPosition).setChecked(true);
}
}
我偶然發現了NavigationView.SavedState,希望這將是一個更好的解決辦法,但我有麻煩弄清楚如何在我的活動中實現這一點。 任何人都可以幫我弄清楚如何實現這個?謝謝。