资料
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
分为两种:
- 一种是
View
的Save/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); }
|