安卓ApiDemos学习 app/Activity/PersistentState

来源:互联网 发布:网络已连接,但无法上网 编辑:程序博客网 时间:2024/05/16 06:55

这个例子展示SharedPreferences的使用

首先取得SharedPreferences对象

SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE);

一般有如下3种取值

MODE_PRIVATE私有int值为0 

MODE_WORLD_READABLE可读int值为1 

MODE_WORLD_WRITEABLE可写int值为2


存储后,会在系统内生成一个存储文件。

如果是MODE_PRIVATE,就只能本App使用,如果为MODE_WORLD,则其他App也可以使用。


第二部,取得SharedPreferences 中存储的值

String restoredText = prefs.getString("text", null);

第一个参数是key,第二个参数是如果取不到值时候的默认值。


在本例子中,有如下代码存储了选中状态

        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);            }        }

其中,下句是往第一个EditText写入文字
mSaved.setText(restoredText, TextView.BufferType.EDITABLE);

最后一步,Activity状态变化时,保存画面信息,包括文字,选择情况等。

    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();    }

效果如下


原创粉丝点击