Activity、Fragment状态缓存和恢复

资料

Activity/Fragment状态缓存和恢复的最佳实践
译文

总结

Activity

Activity中已经自己实现了。
只要重写onSaveInstanceState()onRestoreInstanceState()这两个方法即可

1
2
3
4
5
6
7
8
9
10
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key", "value");
super.onSaveInstanceState(outState);
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String value = savedInstanceState.getString("key");
Log.i(TAG, "onRestoreInstanceState: "+value);
}

Fragment

Fragment分为两种:

  • 一种是ViewSave/Restore
  • 另一种是Fragment自身数据的Save/Restore

View的Save/Restore

Activity一样,在View内部实现onSaveInstanceState()onRestoreInstanceState()即可。
如果是第三方的View,则写一个子类手动实现Save/Restore即可。

Fragment的Save/Restore

在Fragment内部实现onSaveInstanceState()onActivityCreated()即可。

1
2
3
4
5
6
7
8
9
10
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key", "value");
super.onSaveInstanceState(outState);
}

protected void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String value = savedInstanceState.getString("key");
Log.i(TAG, "onRestoreInstanceState: "+value);
}