首页 > 移动平台 > 详细

【起航计划 008】2015 起航计划 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 保存状态 SharedPreferences onPause onResume

时间:2015-03-02 12:44:39      阅读:345      评论:0      收藏:0      [点我收藏+]

Android 提供了多种存储数据的方法,其中最简单的是使用Shared Preferences. Shared Preferences 可以存储 Key/value 对,Shared Preferences 支持存取 boolean, float ,long ,integer, string ,最常用的使用Shared Preferences是用来存储一些应用偏好。此外的一个方法是使用onSaveInstanceState(),这是特别用来保存UI 状态的。

此外的一个方法是使用onSaveInstanceState(),这是特别用来保存UI 状态的。

App->Activity->Persistent State 使用了Shared Preferences来保持部分UI状态(TextView的值)。

创建或是修改Shared Preferences,使用getSharedPreferences(String name, int mode)方法。Shared Preferences 用于单个Application不同Activity之间共享一些数据,但不能用于不同Application之间共享数据。

SharedPreferences.Editor 用来给Shared Preferences添加数据: editor.putXXX(key,value):

    /**
     * Any time we are paused we need to save away the current state, so it
     * will be restored correctly when we are resumed.
     */
    @Override
    protected void onPause() {
        super.onPause();

        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("text", mSaved.getText().toString());
        editor.putInt("selection-start", mSaved.getSelectionStart());
        editor.putInt("selection-end", mSaved.getSelectionEnd());
        editor.commit();
    }

读取Shared Preference: pref.getXXX(key)

    /**
     * Upon being resumed we can retrieve the current state.  This allows us
     * to update the state if it was changed at any time while paused.
     */
    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferences prefs = getPreferences(0); 
        String restoredText = prefs.getString("text", null);
        if (restoredText != null) {
            mSaved.setText(restoredText, TextView.BufferType.EDITABLE);

            int selectionStart = prefs.getInt("selection-start", -1);
            int selectionEnd = prefs.getInt("selection-end", -1);
            if (selectionStart != -1 && selectionEnd != -1) {
                mSaved.setSelection(selectionStart, selectionEnd);
            }
        }
    }

 

技术分享

Persistent State 演示了如何使用Shared Preferences在Activity 恢复时保持EditText的内容。 单是更一般的方法是使用onSaveInstanceState.

 

【起航计划 008】2015 起航计划 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 保存状态 SharedPreferences onPause onResume

原文:http://www.cnblogs.com/dongdong230/p/4308215.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!