我发现了许多类似问题的实例,但不幸的是,没有答案符合我的要求。
我在一个活动中有很多片段,并且我从一个片段传输到另一个片段。该对象将由每个片段修改,我希望在回栈时可以恢复以前的片段实例和使用onSaveInstanceState尝试过的对象的先前版本,但是显然在片段中备份时onSaveInstanceState不被称为< / p>
override fun onSaveInstanceState(outState: Bundle) {
outState?.run {
putParcelable("PRODUCT",Product)
}
super.onSaveInstanceState(outState)
}
答案 0 :(得分:0)
修改片段时,需要创建一个新片段,并.replace
创建一个旧片段。
public BlankFragment modifyFragment() {
int newVar = myVar; // your modified variable. Not the best example
// you need to create a new instance of the fragment
// everytime you modify your fragment so that you can replace the
// one you want to go back to later
BlankFragment blankFragment = BlankFragment.newInstance(++newVar);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.a_main_fl_root, blankFragment) // When you click back press. It will restore the replaced fragment.
.addToBackStack(null)
.commit();
return blankFragment; // the new fragment is returned so you can replace it again and again.
// what I didn't include is how to get the instance of the replaced fragment when you click back press.
}
不需要saveInstanceState,因为它仅在活动被销毁并重新创建时才使用。