美文网首页
保存恢复Activity状态

保存恢复Activity状态

作者: 叙忆 | 来源:发表于2017-10-16 15:21 被阅读0次

    横竖屏切换时,有时候布局文件layout需要重新加载,因此先要销毁Activity对象,再新建;导致状态无法被保存
    解决办法

    1. 不让旋转屏幕
     <activity android:name=".OtherActivity" 
               android:screenOrientation="portrait">
     </activity>
    
    1. 实现自己处理横竖屏变化,无需系统重启Activity
    <activity android:name=".OtherActivity"
              android:configChanges="orientation|keyboardHidden|screenSize">
    </activity>
    
    1. 系统处理配置变更
    • onSaveInstanceState
    • onCreate
    • onRestoreInstanceState
    什么时候需要保存onSaveInstanceState
    • 当点击HOME键(Activity变为后台,系统有可能回收activity,因此需要保存状态)
    • 旋转屏幕
    • 用户拨打电话
    • 按返回键不需要保存状态
    视图状态保存
    • 控件id要一致,横屏layout与竖屏layout中
    • 实现代码如下
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            //!!!!!!!调用父类
            super.onRestoreInstanceState(savedInstanceState);
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
             //!!!!!!!调用父类
            super.onSaveInstanceState(outState, outPersistentState);
        }
    
    • TextView源码分析,实现了onRestoreInstance方法
        @Override
        public void onRestoreInstanceState(Parcelable state) {
            if (!(state instanceof SavedState)) {
                super.onRestoreInstanceState(state);
                return;
        ....
       }
    
        @Override
        public Parcelable onSaveInstanceState() {
            Parcelable superState = super.onSaveInstanceState();
        .....
       }
    

    因此当我们自定义控件的时候,也需要重写,需要调用父类的
    onSaveInstance方法
    onRestoreInstance方法

    • 实例:onCreate中判断Bundle是否为空,初次创建Activity时,bundle为空
    public class OtherActivity extends AppCompatActivity {
    
        public String name="";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_other);
    
            //也可以选择放在onRestoreInstanceState  start
            if (savedInstanceState!=null) {
                name=savedInstanceState.getString("name");
            }else{
                name="请输入名字";
            }
            //end
        }
    
        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            //保存状态
            savedInstanceState.putString("name","Zhang");
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
            super.onSaveInstanceState(outState, outPersistentState);
        }
    }
    

    相关文章

      网友评论

          本文标题:保存恢复Activity状态

          本文链接:https://www.haomeiwen.com/subject/pwlkuxtx.html