Android 保存Activity的状态
2010-05-31 14:41:00 来源:WEB开发网SharedPreferences uiState = getPreferences(0);
// Get the preferences editor.
SharedPreferences.Editor editor = uiState.edit();
// Add the UI state preference values.
editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString());
editor.putBoolean(ADDING_ITEM_KEY, addingNew);
// Commit the preferences.
editor.commit();
}
3. 编写一个restoreUIState方法,当程序重启时,应用在第2步中记录的实例的值。
修改onCreate方法,在最后部分添加对restoreUIState方法的调用。
@Override
public void onCreate(Bundle icicle)
{
[ ... existing onCreate logic ... ]
restoreUIState();
}
private void restoreUIState()
{
// Get the activity preferences object.
SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
// Read the UI state values, specifying default values.
String text = settings.getString(TEXT_ENTRY_KEY, “”);
Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);
// Restore the UI to the previous state.
if (adding)
{
addNewItem();
myEditText.setText(text);
}
}
4. 使用onSaveInstanceState/onRestoreInstanceState机制来记录当前选择的项目的索引。它仅在非用户显式的指令杀死应用程序时保存和应用。
@Override
public void onSaveInstanceState(Bundle outState)
{
outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition());
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
int pos = -1;
if (savedInstanceState != null)
if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);
myListView.setSelection(pos);
}
当你运行To-Do List程序时,你应该看到了在会话期间UI状态的保存。但是,它还不能保存to-do列表的项目——你将在本章的后面添加这个核心的功能。
更多精彩
赞助商链接