Save and restore a ButtonText when screen orientation is switched

我的未来我决定 提交于 2020-01-16 18:28:08

问题


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?


回答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).




回答2:


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



来源:https://stackoverflow.com/questions/4117691/save-and-restore-a-buttontext-when-screen-orientation-is-switched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!