我有一个带有n个条目(在列表视图中)的导航抽屉,如Android Studio中的SDK示例.
当我点击导航栏的条目我希望他们被添加到后面的堆栈,所以我可以回到他们.
在onNavigationDrawerItemSelected(int pos)我有
FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if (position == 0) { transaction.replace(R.id.container,new FragmentA()); } else if (position == 1) { transaction.replace(R.id.container,new FragmentB()); } else { transaction.replace(R.id.container,new FragmentC()); } transaction.addToBackStack(null); transaction.commit();
当我点击抽屉中的第二个条目时,B被选中并替换A.如果我之后点击后退按钮,片段A再次被显示,应该是这样,但在导航栏中仍然选择了B.
退货后,如何更新抽屉的选择状态?
不知怎的,我需要调用mDrawerListView.setItemChecked(position,true);或NavigationDrawerFragment.selectItem(int position).但是哪个位置?我如何预测它?
拦截onBackPressed?
@Override public void onBackPressed() {}
但是我怎么知道哪个片段又活跃了?和它对应的位置.
有没有一些简单的解决方案,我是盲目的看到?似乎使用后退与导航抽屉并更新选择状态是一种标准模式.
解决方法
If your application updates other user interface elements to reflect
the current state of your fragments,such as the action bar,remember
to update the UI when you commit the transaction. You should update
your user interface after the back stack changes in addition to when
you commit the transaction. You can listen for when a
FragmentTransaction
is reverted by setting up a
FragmentManager.OnBackStackChangedListener
:
getSupportFragmentManager().addOnBackStackChangedListener( new FragmentManager.OnBackStackChangedListener() { public void onBackStackChanged() { // Update your UI here. } });
这将是在导航栏中刷新当前选项的正确位置.