Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 活动状态保存和还原帮助程序_Java_Android_Bundle_Savestate - Fatal编程技术网

Java 活动状态保存和还原帮助程序

Java 活动状态保存和还原帮助程序,java,android,bundle,savestate,Java,Android,Bundle,Savestate,我想编写一些帮助程序,从Bundle保存活动状态并将其恢复到Bundle中 重写方法onCreate(Bundle savedState)和onSaveInstanceState(Bundle outState)仍然是必要的,但简单的表单保存/还原有点无聊 大概是这样的: class StateHelper { static void restore(Bundle bundle, String[] properties, Object[] connections){ f

我想编写一些帮助程序,从Bundle保存活动状态并将其恢复到Bundle中

重写方法
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状态,如下所述:

默认实现通过对层次结构中具有id的每个视图调用onSaveInstanceState(),并通过保存当前关注的视图的id(所有视图都由onRestoreInstanceState(Bundle)的默认实现还原),为您处理大多数UI逐实例状态。如果重写此方法以保存每个视图未捕获的其他信息,则可能需要调用默认实现,否则请准备好自己保存每个视图的所有状态


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

像EditText或Checkbox这样的视图会自动保存/恢复它们的状态,您不需要手动执行。还原发生在
onrestoreinnstancestate(Bundle)
中,因此如果重写此方法,请不要忘记调用
super.onrestoreinnstancestate(Bundle)