屏幕方向切换时保存和恢复 ButtonText

发布于 2024-10-01 17:18:31 字数 212 浏览 0 评论 0原文

和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木有鱼丸 2024-10-08 17:18:31

我遇到了同样的问题,并期望默认实现能够恢复按钮的文本。不幸的是没有。最后我找到了属性 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

被你宠の有点坏 2024-10-08 17:18:31

步骤#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 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文