当屏幕旋转时,onSaveInstanceState()不工作。

可能,我的代码是正确的,但是当屏幕旋转时,onSaveInstanceState()方法不工作。活动销毁后数据不保存(onDestroy()有效)。但是,在方法onPause()和onStop()之后,该方法可以工作。活动中有一个元素–textView,当方法工作时,我写了文本。有错误的地方吗?先谢谢你。

    public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        textView = findViewById(R.id.textView);

        if (savedInstanceState != null)
        {
           textView.setText(savedInstanceState.getString("saveInstance"));
        }

        Log.i("lifecycle show", "onCreate() worked");
        textView.append("onCreate() worked\n");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("lifecycle show", "onStart() worked");
        textView.append("onStart() worked\n");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("lifecycle show", "onResume() worked");
        textView.append("onResume() worked\n");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("lifecycle show", "onRestart() worked");
        textView.append("onRestart() worked\n");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("lifecycle show", "onPause() worked");
        textView.append("onPause() worked\n");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("lifecycle show", "onStop() worked");
        textView.append("onStop() worked\n");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("lifecycle show", "onDestroy() worked");
        textView.append("onDestroy() worked\n");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("lifecycle show", "onSaveInstanceState() worked");
        textView.append("onSaveInstanceState() worked\n");
        outState.putString("savedInstance", textView.getText().toString());
    }
}

解决方案:

错误的标签。你用 “saveInstance “作为标签放入字符串,然后通过标签 “saveInstance “得到字符串。

给TA打赏
共{{data.count}}人
人已打赏
未分类

连体

2022-9-9 5:30:23

未分类

为什么File.WriteAllText不向文件写入数据?

2022-9-9 5:41:17

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索