片段保存视图状态 [英] Fragment save view state
问题描述
我有一些具有这种结构的片段:
I have some Fragment with this structure:
<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类中,我有 onSaveInstanceState
和 onActivityCreated
:
And inside Fragment class i have onSaveInstanceState
and onActivityCreated
:
@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
的状态的问题.
So it solves saving the state of TextView
.
在Fragment类中,我还设置了要显示某些功能的图像:
Inside Fragment class I also setup which image to display with some function:
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);
}
}
有什么方法可以保存和恢复当前显示的图像?
Is there any way to save and restore which image is currently displayed?
我知道,我不应该保存整个小部件,但是如果我可以保存 RelativeLayout
的状态,它将恢复所有子状态吗?
I know, what I'm shouldn't save entire widgets, but if I can save state of RelativeLayout
will it restore all it's child's states?
推荐答案
在Fragment类中,声明一个私有变量:
Inside your Fragment class, declare a private variable:
private boolean condition; // rename to something more descriptive
现在在 setIcon()
中存储值:
this.condition = condition;
最后将其保存到 onSaveInstanceState()
中的捆绑软件中:
Finally save this to the bundle in onSaveInstanceState()
:
outState.putBoolean("condition", this.condition);
并在 onActivityCreated()
中读取它:
this.condition = savedInstanceState.getBoolean("condition");
this.setIcon(this.condition);
注意
您无需保存 TextView
中的文本.对 super.onSaveInstanceState()
的调用已经为您完成了此工作.
You don't need to save the text from your TextView
. The call to super.onSaveInstanceState()
already takes care of this for you.
这篇关于片段保存视图状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!