屏幕方向切换时保存和恢复 ButtonText
和 Android 中一样,每次屏幕翻转到纵向/横向模式时,Activity 都会经历从 onSaveInstanceState 到 onDestroy 的生命周期,然后重新创建。
在我的活动中,有一个可由用户更改的 ButtonText。它已重置为初始状态,但我必须以某种方式保存最后一个状态。我怎样才能实现这一点,我必须重写 onSaveInstanceState 吗?有人可以举个例子吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了同样的问题,并期望默认实现能够恢复按钮的文本。不幸的是没有。最后我找到了属性 android:freezesText 和方法 setFreezesText(boolean)。当设置为 true 时,按钮将自动恢复其文本。
请参阅Button的超类TextView的参考:http://developer. android.com/reference/android/widget/TextView.html#attr_android:freezesText
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
步骤#1:在
Button
上调用getText().toString()
以获取标题。步骤 #2:在传递给
onSaveInstanceState()
实现的Bundle
上调用putString()
以存储标题。步骤#3:在传递给
onRestoreInstanceState()
实现的Bundle
上调用getString()
(或在onCreate()< /code>,如果
将标题放回原位。Bundle
不是null
(如果您愿意))要取回您的标题,然后在setText()
上调用setText()
code>Button这里是一个示例项目,它使用
onSaveInstanceState()
保存联系人的Uri
(这也会影响Button
是否为已启用)。Step #1: Call
getText().toString()
on theButton
to get the caption.Step #2: Call
putString()
on theBundle
passed to your implementation ofonSaveInstanceState()
to store the caption.Step #3: Call
getString()
on theBundle
passed to your implementation ofonRestoreInstanceState()
(or inonCreate()
, if theBundle
is notnull
, if you wish) to get your caption back, then callsetText()
on yourButton
to put the caption back in.Here is a sample project that uses
onSaveInstanceState()
to save aUri
of a contact (which also affects whether or not aButton
is enabled).