2015-04-01 64 views
0

我的Android應用程序有一些奇怪的東西。碎片和Android生命週期

如果我運行主要活動,然後通過幾個片段,隱藏/取消隱藏應用程序後,我會看到主要活動。如果我按下「後退」,它將顯示隱藏之前顯示的片段。但有時應用程序顯示我隱藏後的最後一個片段。如果可能,我怎樣才能讓我的應用程序每次顯示最後一個片段?或者我如何讓我的應用程序保存其狀態?

+0

我想你必須在onSaveInstance()中保存當前片段的數量,並使用這個數字來重載onCreate方法中的片段。在這裏檢查:http://developer.android.com/training/basics/activity-lifecycle/recreating.html – Maxouille 2015-04-01 14:47:57

+0

看看這裏:http://developer.android.com/training/implementing-navigation/temporal.html。雖然不太清楚你的問題(..隱藏/取消隱藏應用程序部分),但我認爲這可能是一個後端堆棧管理問題。 – Dexter 2015-04-01 15:03:02

+0

@Maxouille,但我想運行完全相同的片段。 – Tony 2015-04-01 15:04:59

回答

1

如果我理解,你想要當按下「後退」按鈕時,應該顯示最後一個片段。爲此,您可以依靠addToBackStack方法來處理背部按壓。 從谷歌代碼片斷@Fragments

Fragment newFragment = new ExampleFragment(); 
FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

// Replace whatever is in the fragment_container view with this fragment, 
// and add the transaction to the back stack 
transaction.replace(R.id.fragment_container, newFragment); 
transaction.addToBackStack(null); 

// Commit the transaction 
transaction.commit(); 

注:在這種情況下newFragment是你的最後一個片段。