Android API Demos学习(3) - Persistent State
例子展示了关闭程序时怎么持久保存用户偏好。
@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);
}
}
}
1. 在onResume方法中恢复状态,因为程序要进入运行,必须会执行这个方法。
2. SharedPreferences以key/value的方式保存信息。
3. setSelection设置光标和选择信息。
www.zzzyk.com
@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();
}
1.
补充:移动开发 , Android ,