活动状态保存和恢复助手

问题描述:

我想写某种帮手来保存和/恢复活动状态的线束活动状态保存和恢复助手

重写方法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); 

然后我会花一整天的时间创建这个,我的问题是,有没有类似的帮助类或本地方式如何做到这一点简单的保存/恢复操作?

通常,如果您通过super.onSaveInstanceState进行调用,则不需要像在助手中显示的那样保存UI状态。 Android框架需要保存UI状态中规定的照顾javadocs

默认实现由层次结构中的每个视图调用的onSaveInstanceState()需要照顾大多数UI每个实例的状态为你的那个有一个ID,并通过保存当前焦点视图的ID(所有这些都通过onRestoreInstanceState(Bundle)的默认实现来恢复)。如果您重写此方法以保存未被每个视图捕获的附加信息,那么您可能需要调用默认实现,否则应准备好保存每个视图的所有状态。

因此,为了保存UI状态,它是内置的,为了保存您的应用程序的其他状态,您需要一些自定义逻辑。我不认为有任何通用的实用类。

+0

啊,错过了那一点。谢谢 –

像EditText或复选框视图自动保存/恢复他们的状态,你不需要手动。恢复发生在onRestoreInstanceState(Bundle),所以如果您重写此方法,请不要忘记拨打super.onRestoreInstanceState(Bundle)