2017-06-27 69 views
0

最初我有一個活動A在其中我要打開一個片段,所以在這裏如何保存該片段 因此,當我在銷燬它後啓動我的應用程序恢復該片段在同一活動中這裏相同的位置保存碎片事務無論如何

因爲,方便回答我的片段交易代碼:

Fragment newFragment = new ece_frag(); 
    FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
    transaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out); 
    transaction.replace(R.id.frame_layout, newFragment); 
    transaction.commit(); 
+0

將此置於創建活動。所以無論何時創建活動,都會將該片段添加到該片段中。 –

+0

實際上我想在點擊按鈕時應用這個片段 –

+0

使用共享的首選項,那麼你可以通過索引所有片段來保存索引。然後在onCreate中檢查最後一個片段是什麼並加載它。 –

回答

1

比方說你有3個碎片A,B和C

我給指數的每個片段這樣說0- > A,1-> B,2-> C。所以,當我這樣做,我也拯救像下面的代碼索引:

Fragment newFragment = new A(); 
FragmentTransaction transaction = 
getFragmentManager().beginTransaction(); 
transaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out); 
transaction.replace(R.id.frame_layout, newFragment); 
transaction.commit(); 
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putInt("last_fragment", 0);//For fragment A saving index 0 
editor.commit(); 

然後在的onCreate就可以,如果使用的情況下是這樣的:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
//0 here is the default value 
int lastFragment = sharedPref.getInt("last_fragment", 0); 

然後你就可以做到這一點

switch(lastFragment){ 
    case 0: 
    //Load your fragment Here according to the index. 
    break; 
    case 1: 
    //Load your fragment Here according to the index. 
    break; 
    case 2: 
    //Load your fragment Here according to the index. 
    break; 

} 

希望這會有所幫助。

+0

在案件0我已經使用以前的代碼片段交易,我問 –

+0

,它不是這樣工作 –

+0

一個嚴重的謝謝你,我是從這兩天的這個答案... –