Android 退出前保存片段事务的正确方法
我有我在mainActivity中替换Android 退出前保存片段事务的正确方法,android,android-fragments,Android,Android Fragments,我有我在mainActivity中替换片段的方法。。单击我的按钮后,就像这样。 FragmentTransaction trans = getSupportFragmentManager().beginTransaction(); Fragment2 f2=new Fragment2(); trans.replace(R.id.root_frame, f2,"Fragment2"); trans.setTransition(FragmentTransaction.TRAN
片段的方法。。单击我的按钮后,就像这样。
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
Fragment2 f2=new Fragment2();
trans.replace(R.id.root_frame, f2,"Fragment2");
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.commit();
getPager().setCurrentItem(0);
在退出我的应用程序之前,我需要保存此更改。因此,当我重新打开我的应用程序时,事务更改将出现…您可以在共享首选项中保存片段状态,并在片段重新创建时检索它
设置事务时保存状态
SharedPreferences mypreferences=getActivity().getPreferences(MODE_PRIVATE);
Editor editor= mypreferences.edit();
editor.putString("transition","FragmentTransaction.TRANSIT_FRAGMENT_OPEN");
//do the same for other fragment states
editor.commit();
在onCreate()方法中检索您的状态
太多了…你救了我一天。。。(:还有一个问题,因为我现在无法尝试此操作…我是否必须在onCreate()中再次调用transaction.replace(),或者重新打开后片段将被替换…我仍在学习是的,在onCreate()中的所有情况下,您仍然必须调用replace方法。快乐编码:)
String transition= mypreferences.getString("transition", "");
if(!transition.equals(""){
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
//do the same for other fragment states
}