显示前一个片段

如何删除当前和显示前一个片段? 就像我按“返回”button

我正在使用这样的结构:

FragmentManager fm=getFragmentManager(); FragmentTransaction ft=fm.beginTransaction(); ft.remove(fragment).commit(); 

但它只是删除当前片段,而不显示以前

Solutions Collecting From Web of "显示前一个片段"

你必须调用FragmentTransaction.addToBackStack(null)在你添加片段的地方,然后当你想删除它时调用FragmentManager.popBackStack()

在您的活动中添加此方法:

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if( this.getFragmentManager().getBackStackEntryCount() != 0 ){ this.getFragmentManager().popBackStack(); return true; } // If there are no fragments on stack perform the original back button event } return super.onKeyDown(keyCode, event); } 

那么你在哪里改变的片段做到这一点:

 FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(android.R.id.content, new YourFragmentName()); transaction.addToBackStack(null); // this is needed for the above code to work transaction.commit(); 

尝试删除后显示前一个片段:

  FragmentManager fm=getSupportFragmentManager(); FragmentTransaction ft=fm.beginTransaction(); ft.remove(fragment).commit(); previousFragment=(SherlockFragment)getSupportFragmentManager() .findFragmentByTag(""+currentTagNum); getSupportFragmentManager().beginTransaction() .show(mFragment) .commit();