如何使用 onSavedInstance 方法防止在更改为横向模式时丢失数据



我正在制作推特集成的示例,我正在单击按钮获取用户信息。数据出现在屏幕上,它与纵向模式b一起工作正常,但是当我更改为横向模式时,数据丢失。

如何解决这个问题,我不知道如何使用onSavedInstance方法来解决这个问题。 请帮忙

您需要

覆盖 android 默认方法,如 onSaveInstanceStateonRestoreInstanceState检查此示例。

 @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
        savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // Always call the superclass first
        // Check whether we're recreating a previously destroyed instance
        if (savedInstanceState != null) {
            // Restore value of members from saved state
            mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
            mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
        } else {
            // Probably initialize members with default values for a new instance
        }
        ...
    }
   //you can retrieve saved values from here 
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
        // Restore state members from saved instance
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    }

单击此处以查找有关此内容的更多信息

最新更新