java - Activity State保存和恢复Helper

标签 java android bundle savestate

我想编写某种帮助程序来保存和恢复 Bundle 中的 Activity 状态

重写方法onCreate(Bundle savingState)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);

在我花一整天的时间来创建这个之前,我的问题是,是否有任何类似的帮助程序类或 native 方法来执行这个简单的保存/恢复操作?

最佳答案

通常,如果您调用 super.onSaveInstanceState,则不需要像在助手中那样保存 UI 状态。 Android 框架负责保存 UI 状态,如 javadocs 中所述。 :

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

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

关于java - Activity State保存和恢复Helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309148/

相关文章:

java - 覆盖率与可达代码

java - Spring微服务之间的通信

android - 我可以在 FirebaseMessagingService 中启动前台任务吗?

android - 将整个包(对象)本身从某个 Activity 的 fragment 传递和接收到另一个 Activity

java - 如何在Java中使用PKCS#11 CKM_AES_KEY_WRAP机制?

java - Netty 可以为每个客户端请求发送多个响应吗

android - 在android上获取蓝牙网络共享设备的IP地址

java - 如何诊断Android并发修改异常

java - Android:在多个 Activity 上传递字符串数组

iphone - 抛出 'NSException' (gdb) 实例后调用终止