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

时间:2015-06-14 18:59:18

标签: android

我正在制作一个twitter集成示例,我在点击按钮时获取用户信息。数据即将出现在屏幕上它与肖像模式正常工作,但随着我改为横向模式,数据丢失。

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

1 个答案:

答案 0 :(得分:1)

您需要覆盖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);
    }

click here to find more about this