Android ApiDemos示例解析(9):App->Activity->Persistent State
Android 提供了多种存储数据的方法,其中最简单的是使用Shared Preferences. Shared Preferences 可以存储 Key/value 对,Shared Preferences 支持存取 boolean, float ,long ,integer, string ,最常用的使用Shared Preferences是用来存储一些应用偏好。此外的一个方法是使用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)
[java]
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();
}
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)
[java]
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);
}
}
}
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.
作者:mapdigit
补充:移动开发 , Android ,