在我的应用程序中,我在ViewPager中有Fragment.片段包含RecyclerView,其中包含基于用户选择从web api获取的数据列表.
在我的片段onSaveInstanceState上,我将列表数据保存到Bunde,以保持配置更改等数据.
public void onSaveInstanceState(Bundle savedState) { super.onSaveInstanceState(savedState); savedState.putParcelableArrayList(LIST_STORAGE_KEY,new ArrayList<>(mItemAdapter.getModels())); }
现在我已经开始在我的应用程序错误报告上看到TransactionTooLargeException.
在某些情况下,似乎我放入Bundle的列表太大(因为它是非常复杂的对象的集合).
我该如何处理这个案子?如何存储(和恢复)我的Fragment状态.
在ViewPager中的片段上使用setRetainInstance(true)是否可以?
解决方法
为了保留大块数据,Google建议使用保留实例的Fragment.想法是创建没有视图的空片段和所有必需的字段,否则这些字段将被保存在Bundle中.添加setRetainInstance(true);到Fragment的onCreate方法.而不是将数据保存在Activity的onDestroy上的Fragment中并将它们加载到onCreate上.以下是活动的例子:
public class MyActivity extends Activity { private DataFragment dataFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // find the retained fragment on activity restarts FragmentManager fm = getFragmentManager(); dataFragment = (DataFragment) fm.findFragmentByTag("data"); // create the fragment and data the first time if (dataFragment == null) { // add the fragment dataFragment = new DataFragment(); fm.beginTransaction().add(dataFragment,"data").commit(); // load the data from the web dataFragment.setData(loadMyData()); } // the data is available in dataFragment.getData() ... } @Override public void onDestroy() { super.onDestroy(); // store the data in the fragment dataFragment.setData(collectMyLoadedData()); } }
片段的例子:
public class DataFragment extends Fragment { // data object we want to retain private MyDataObject data; // this method is only called once for this fragment @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // retain this fragment setRetainInstance(true); } public void setData(MyDataObject data) { this.data = data; } public MyDataObject getData() { return data; } }