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

發佈留言