保存碎片事务无论如何

问题描述:

最初我有一个活动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中检查最后一个片段是什么并加载它。 –

比方说你有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

一个严重的谢谢你,我是从这两天的这个答案... –