Activity小结02 -- 值保存、状态恢复
1.当activity不小心被销毁时保存相关值,重新创建时拿到值:
-
activty销毁时,调用activity的onSaveInstanceState方法保存值
-
在activity重新创建时调用onRestoreInstanceState或者onCreate方法拿到值
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//拿值,方式1
if(savedInstanceState!=null){
String test = savedInstanceState.getString("test");
}}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//存值
outState.putString("test","test");
}@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//拿值,方式2
String test = savedInstanceState.getString("test");
}
1.1 onRestoreInstanceState方法拿值好处
- 不需判断onRestoreInstanceState方法中的savedInstanceState是否为空,再拿值,相比onCreate方法中的savedInstanceState则要先判断是否为空,因为第一次启动activity,savedInstanceState为null
- 官网推荐
2.防止系统配置改变,重新创建Activity
常见场合:弹出软键盘、屏幕旋转
在androidMenifest.xml中对应activity标签配置android:configChanges属性,指定多个值,用”|“分隔
<activity
android:name=".activity.TestActivity"
android:configChanges=”oritentation|keyboardHidden“>
</activity>
网友评论