2011-11-29 163 views
0

我想寫某種幫手來保存和/恢復活動狀態的線束活動狀態保存和恢復助手

重寫方法onCreate(Bundle savedState)onSaveInstanceState(Bundle outState)仍然是必要的,但簡單的形式保存/恢復是有點兒無聊

事情是這樣的:

class StateHelper { 

    static void restore(Bundle bundle, String[] properties, Object[] connections){ 
     for(int i = 0; i < properties.length; i++){ 
      if(bundle.containsKey(properties[i])){ 
       restoreState(properties[i], connections[i]); 
      } 
     } 
    } 

    static void save(Bundle bundle, String[] properties, Object[] connections){ 
     for(int i = 0; i < properties.length; i++){ 
      saveState(properties[i], connections[i]); 
     } 
    } 

    restoreState(String s, Object o){ 
     if(o instanceof EditText){ 
      // restore state with getString 
     } else if(o instanceof Checkbox){ 
      // save state with getBoolean 
     } 
     // etc. etc. handle all UI types 
    } 

    saveState(String s, Object o){ 
     // similar to restoreState(String, Object) 
     // only saving instead of restoring 
    } 
} 

,並使用這樣的:

String[] props = {LOGIN,PASSWORD,REALNAME}; 
Object[] cons = {textedit_login, textedit_password, textedit_realname}; 
StateHelper.restore(savedState, props, cons); 
// or 
StateHelper.save(outBundle, props, cons); 

然後我會花一整天的時間創建這個,我的問題是,有沒有類似的幫助類或本地方式如何做到這一點簡單的保存/恢復操作?

回答

1

通常,如果您通過super.onSaveInstanceState進行調用,則不需要像在助手中顯示的那樣保存UI狀態。 Android框架需要保存UI狀態中規定的照顧javadocs

默認實現由層次結構中的每個視圖調用的onSaveInstanceState()需要照顧大多數UI每個實例的狀態爲你的那個有一個ID,並通過保存當前焦點視圖的ID(所有這些都通過onRestoreInstanceState(Bundle)的默認實現來恢復)。如果您重寫此方法以保存未被每個視圖捕獲的附加信息,那麼您可能需要調用默認實現,否則應準備好保存每個視圖的所有狀態。

因此,爲了保存UI狀態,它是內置的,爲了保存您的應用程序的其他狀態,您需要一些自定義邏輯。我不認爲有任何通用的實用類。

+0

啊,錯過了那一點。謝謝 –

1

像EditText或複選框視圖自動保存/恢復他們的狀態,你不需要手動。恢復發生在onRestoreInstanceState(Bundle),所以如果您重寫此方法,請不要忘記撥打super.onRestoreInstanceState(Bundle)