片段保存视图状态

时间:2018-06-25 11:11:51

标签: android android-layout android-fragments onsaveinstancestate

我有一些具有这种结构的片段:

    <RelativeLayout
        android:id="@+id/control_panel"
        android:visibility="gone">

        <RelativeLayout
            android:id="@+id/control_panel_icon">

            <ImageView
                android:id="@+id/control_panel_icon_1"
                android:src="@drawable/ic_control_panel_icon_1" />

            <ImageView
                android:id="@+id/control_panel_icon_2"
                android:src="@drawable/ic_control_panel_icon_2"
                android:visibility="gone"/>
        </RelativeLayout>

        <TextView
            android:id="@+id/control_panel_tv"
            android:text="@string/not_available" />
    </RelativeLayout>

在Fragment类中,我有onSaveInstanceStateonActivityCreated

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("tv", panel_tv.getText().toString());
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) 
        panel_tv.setText(savedInstanceState.getString("tv"));
}

因此它解决了保存TextView状态的问题。

在Fragment类中,我还设置了要显示某些功能的图像:

public void setIcon(boolean condition){
    if (condition) {
         control_panel_icon_1.setVisibility(View.GONE);
         control_panel_icon_2.setVisibility(View.VISIBLE);
    } else {
         control_panel_icon_1.setVisibility(View.VISIBLE);
         control_panel_icon_2.setVisibility(View.GONE);
    }
}

有什么方法可以保存和恢复当前显示的图像?

我知道,我不应该保存整个窗口小部件,但是如果我可以保存RelativeLayout的状态,它将恢复所有子状态吗?

2 个答案:

答案 0 :(得分:2)

在您的Fragment类中,声明一个私有变量:

private boolean condition; // rename to something more descriptive

现在setIcon()中存储值:

this.condition = condition;

最后将其保存到onSaveInstanceState()中的捆绑软件中:

outState.putBoolean("condition", this.condition);

并在onActivityCreated()中阅读:

this.condition = savedInstanceState.getBoolean("condition");
this.setIcon(this.condition);

注意

您无需保存TextView中的文本。对super.onSaveInstanceState()的呼叫已经为您解决了这个问题。

答案 1 :(得分:2)

您可以将condition保存在outState中,如下所示:

outState.putBoolean("condition", condition);

然后阅读并更新图像视图

setIcon(savedInstanceState.getBoolean("condition"))

或者您可以通过putInt方法保存图像视图的可见性状态:

outState.putInt("ic1", control_panel_icon_1.getVisibility());
outState.putInt("ic2", control_panel_icon_2.getVisibility());

然后恢复状态:

control_panel_icon_1.setVisibility(savedInstanceState.getInt("ic1"));
control_panel_icon_2.setVisibility(savedInstanceState.getInt("ic2"));