问题
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>
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"));
}
So it solves saving the state of TextView
.
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?
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?
回答1:
Inside your Fragment class, declare a private variable:
private boolean condition; // rename to something more descriptive
Now in setIcon()
store the value:
this.condition = condition;
Finally save this to the bundle in onSaveInstanceState()
:
outState.putBoolean("condition", this.condition);
and read it in onActivityCreated()
:
this.condition = savedInstanceState.getBoolean("condition");
this.setIcon(this.condition);
Note
You don't need to save the text from your TextView
. The call to super.onSaveInstanceState()
already takes care of this for you.
回答2:
You can either save the condition
in outState
like below:
outState.putBoolean("condition", condition);
and then read it and update the image views
setIcon(savedInstanceState.getBoolean("condition"))
Or You can save the visibility state of the image views by putInt
method:
outState.putInt("ic1", control_panel_icon_1.getVisibility());
outState.putInt("ic2", control_panel_icon_2.getVisibility());
and then restore the state:
control_panel_icon_1.setVisibility(savedInstanceState.getInt("ic1"));
control_panel_icon_2.setVisibility(savedInstanceState.getInt("ic2"));
来源:https://stackoverflow.com/questions/51022120/fragment-save-view-state