如何在Android中保存LinearLayout的实例状态?

时间:2013-08-15 22:18:46

标签: android save android-linearlayout

在我的应用中,我动态设置了线性布局的可见性。问题是在旋转设备时,线性布局的状态(可见或不可见)不会被保存。

现在我想在保存布局的实例状态的帮助下保存状态。 有人可以用相应的方法帮助我吗?我必须提供什么价值?

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // ??
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // ???
}

2 个答案:

答案 0 :(得分:0)

只需将可见性作为整数存储在Bundle中。

private final static String VIEW_1_VISIBILITY = "view_1_visibility";
private View mView1;

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(VIEW_1_VISIBILITY, mView1.getVisibility());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if(savedInstanceState != null){
        mView1.setVisibility(savedInstanceState.getInt(VIEW_1_VISIBILITY, View.VISIBLE));
    }
}

答案 1 :(得分:0)

您可以通过在包中保存布尔值或整数值来保存实例状态:

private static final VISIBILITY_KEY = "anthing you want";

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    boolean isVisible = . . .;
    outState.putBoolean(VISIBILITY_KEY, isVisible);
}

您可以按如下方式阅读:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    boolean isVisible = savedInstanceState.getBoolean(VISIBILITY_KEY);
    // do something with isVisible
}