0

As usual in android, each time the screen is flipped to portrait/landscape mode an Activity runs through life-cycle from onSaveInstanceState to onDestroy and then is recreated.

In my Activity there's a ButtonText which can be changed by the user. It's reseted to the initial state, but I have to save the last state somehow. How can I achieve that, will I have to override onSaveInstanceState? Can someone show an example?

cody
  • 6,389
  • 15
  • 52
  • 77

2 Answers2

4

I had the same problem and expected that the default implementation would take care of restoring a button's text. Unfortunately it did not. Finally I found the attribute android:freezesText respectively the method setFreezesText(boolean). When set to true the button will restore its text automatically.

See the reference of Button's super class TextView: http://developer.android.com/reference/android/widget/TextView.html#attr_android:freezesText

adre
  • 41
  • 2
  • 1
    This answer works, its as simple as adding `"android:freezesText="true"` to your button XML and button text is saved in orientation changes – btalb Oct 15 '14 at 07:49
1

Step #1: Call getText().toString() on the Button to get the caption.

Step #2: Call putString() on the Bundle passed to your implementation of onSaveInstanceState() to store the caption.

Step #3: Call getString() on the Bundle passed to your implementation of onRestoreInstanceState() (or in onCreate(), if the Bundle is not null, if you wish) to get your caption back, then call setText() on your Button to put the caption back in.

Here is a sample project that uses onSaveInstanceState() to save a Uri of a contact (which also affects whether or not a Button is enabled).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491