最初我有一个活动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 :(得分: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中你可以使用这样的if case:
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;
}
希望这会有所帮助。