2014-01-30 33 views
13

我有一個活動,其中我使用以下方法切換片段:如何從FragmentManager中刪除以前的背堆棧條目?

public void setCurrentFragment(Fragment fragment) { 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    transaction.setCustomAnimations(R.anim.slide_left_right_in, R.anim.slide_left_right_out, R.anim.slide_right_left_in, R.anim.slide_right_left_out); 
    transaction.replace(R.id.contentFrameLayout, fragment, Integer.toString(fragmentId++)); 
    transaction.addToBackStack(Integer.toString(fragmentId)); 
    transaction.commit(); 
} 

我的導航堆棧看起來像這樣:

N-2 - > N-1 - >Ñ

當某個片段N'打開'我希望將前一個片斷(N-1)從後臺堆棧中移除,因此當我按'後退'時,我想要恢復N-2片段。

當我在N片段中調用FragmentManager.popBackStack(..)時,它將刪除N和N-1片段。

我試圖在切換到N片段之前在N-1片段中調用popBackStack(..)。但是在那種情況下,N-2片段被恢復,並且僅在該N片段被顯示之後。

我的問題是:有沒有什麼辦法可以從堆棧中刪除以前的片段而不彈出當前片段?

+0

你有沒有得到任何解決方案,因爲我也面臨同樣的問題? –

回答

1

使用public abstract void popBackStack (int id, int flags)返回堆棧。檢查this 例如getSupportFragmentManager().popBackStack(fragmentId,0);

+5

我已經試過了,它也從我的後臺刪除了我的當前片段。文檔說:'彈出所有返回堆棧狀態直到具有給定標識符的狀態。 「 – nemezis

0

可以使用與上述的一個替代的方法,該方法將不使用 addToBackStack()方法和直接調用提交();