如何刪除當前並顯示前一個片段?就像如果我按「返回」按鈕顯示前一個片段
我使用這樣的結構:
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();
但它只是刪除當前片段,沒有表現出以往
如何刪除當前並顯示前一個片段?就像如果我按「返回」按鈕顯示前一個片段
我使用這樣的結構:
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.remove(fragment).commit();
但它只是刪除當前片段,沒有表現出以往
你必須調用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();
而如果你這樣做,你將不必重寫BACK按鈕的行爲。可見片段將自動被移除,當您按下BACK時,後臺堆棧中的下一個片段將自動顯示。 – 2012-02-01 19:17:01
這不適用於我我正在使用v4庫。 – 2014-01-30 09:18:18
FragmentManager.popBackStack()重新加載片段。 – 2014-02-17 06:35:43