Reputation: 3423
This is not a duplication from the 'how to setVisibility' questions.
I have an activity 1 and an activity 2, when I start activity 2 I set a layout from Gone to Visible in a Listener and it works, my problem is, when I return to activity 1 and go back into activity 2, the layout's visibility is back to Gone. How do I make the layout stay Visible when I leave it?
Activity2.java:
@Override
public void onClick(View v) {
if (FirstLayout.getVisibility() == View.INVISIBLE) {
FirstLayout.setVisibility(View.VISIBLE);
}
}
Activity2.xml:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:id="@+id/oneLayout"
android:animateLayoutChanges="true"
android:orientation="vertical">
<!-- one Button -->
<!-- one TextView -->
</LinearLayout>
Upvotes: 0
Views: 2096
Reputation: 1366
As said in comments above, in your Activity2.java:
SharedPreferences sharedPreferences;
and in the onCreate method at Activity2:
sharedPreferences=getPreferences(Context.MODE_PRIVATE);
FirstLayout.setVisibility(sharedPreferences.getBoolean("visibility",false));
and then:
@Override
public void onClick(View v) {
if (FirstLayout.getVisibility() == View.INVISIBLE) {
FirstLayout.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("visibility",true).commit();
}
}
Upvotes: 1
Reputation: 3654
you can save your last state via following method
boolean mState = false;
final String STATE_VISIBILITY = "state-visibility";
// somewhere in the code assign a value to mState
// i.e. mState = false (if GONE default) and mState = true (if VISIBLE)
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putBoolean(STATE_VISIBILITY, mState);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and restore
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mState = savedInstanceState.Boolean(STATE_VISIBILITY);
view.setVisibility(mState?View.VISIBLE:View.GONE);
}
More on http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Upvotes: 1