Android Save Instance - 最佳实践

时间:2015-12-26 13:14:12

标签: android variables bundle instance

因此,为了保存我的Fragment实例,我使用了一个Bundle,我保存在onSaveInstanceState中并在onActivityCreated中恢复。现在我想知道最佳做法是什么:

1)有一个用于存储变量的包,并根据需要在代码中使用/更新。这样节省和恢复状态'代码很短。像这样:

private Bundle mDataValues = new Bundle();

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if ( (savedInstanceState != null) && (savedInstanceState.getBundle("mDataValues") != null) ) {
        this.mDataValues = savedInstanceState.getBundle("mDataValues");
}

public void someFunction() {
    if (this.mDataValues == null) {
        // Should not be possible on the times we call this function
        return;
    }
    usernameView.setText(mDataValues.getString(Constants.BUNDLE_KEY_USERNAME));
    personnameView.setText(mDataValues.getString(Constants.BUNDLE_KEY_PERSONNAME));
}

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putBundle("mDataValues", mDataValues);
}

2)在片段中声明了一堆变量,并在代码中使用这些变量。像这样:

private String mUsername;
private String mPersonname;

@Override
public void onActivtyCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if ( savedInstanceState != null ) {
        mUsername = savedInstanceState.getString("username");
        mPersonname = savedInstanceState.getString("personname");
    }

}

public void someFunction() {
    usernameView.setText(mUsername);
    personnameView.setText(mPersonname);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString("username", mUsername);
    outState.putString("personname", mPersonname);
}

上面的变量数量当然比编写的实际代码少很多。那么最佳做法是什么?或者在特定情况下都可行吗?

0 个答案:

没有答案