我有抽屜式導航菜單結構目前設置爲允許回到以前的fragmnet,與addToBackStack,選擇後退按鈕當:Android的後退按鈕定位到特定的片段
if (menuItem.getItemId() == R.id.nav_item_messages) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new MessageTabFragment()).addToBackStack("MainActivity").commit();
}
不過,我想允許後退按鈕始終將用戶發送回特定的幀,而不僅僅是前一幀。
這是如何實現的?
修正
我試圖加入的代碼:
int homeFragmentIdentifier = -1;
...
if (menuItem.getItemId() == R.id.nav_item_messages) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
if(homeFragmentIdentifier == -1) {
homeFragmentIdentifier = xfragmentTransaction.replace(R.id.containerView, new MessageTabFragment()).commit();
} else {
xfragmentTransaction.replace(R.id.containerView, new MessageTabFragment()).commit();
}
}
...
@Override
public void onBackPressed() {
super.onBackPressed();
getFragmentManager().popBackStack(homeFragmentIdentifier, 0);
}
但它只是簡單地調用錯誤:
01-15 19:31:55.368 18410-18410/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.feastappv2, PID: 18410
java.lang.IllegalArgumentException: Bad id: -1
at android.app.FragmentManagerImpl.popBackStack(FragmentManager.java:526)
at com.example.android.feastappv2.feastapp.MainActivity.onBackPressed(MainActivity.java:143)
at android.app.Activity.onKeyUp(Activity.java:2667)
at android.view.KeyEvent.dispatch(KeyEvent.java:3214)
at android.app.Activity.dispatchKeyEvent(Activity.java:2922)
您仍需調用'xfragmentTransaction.addToBackStack(String)'或'commit()'將始終返回-1。 –