方向更改上的Android按钮状态 [英] Android Button State on Orientation Change

查看:35
本文介绍了方向更改上的Android按钮状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在保持按钮状态时遇到问题-说 Button1.setActivated(true).更改方向后,该操作将被忘记,并且不会重新激活或显示为已激活.

I have a problem keeping the state of my buttons - say Button1.setActivated(true). When orientation is changed this is forgotten and it is not reactivated or shown as activated.

我想我可以使用IF来测试Button状态的状态,将其存储在变量中,然后使用onSaveInstanceState/onRestoreInstanceState返回它.然后在重新创建每个按钮时对其添加更多检查.但这似乎是一种复杂的工作方式.

I guess I could use IFs to test the status of Button state, store it in a variable and then return it with onSaveInstanceState/onRestoreInstanceState. And then add more checks on each button when it is recreated. But that seems a massive convoluted way of doing things.

肯定会有更好的方法吗?

Surely there will be a better way to do this?

我还是Android的新手,所以我可能会遗漏一些明显的东西.

I'm still pretty new to Android so I could be missing something obvious.

谢谢.

更新:setActivated使用选择器更改按钮的背景颜色.正是这种颜色在方向改变中被遗忘了.

Update: The setActivated changes the background colour of the button using a selector. It is this colour that is forgotten in orientation change.

button_selector_background.xml

button_selector_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/button_background_active"
      android:state_activated="true" />

    <item android:drawable="@color/button_background" />

</selector>

MainActivity.java

MainActivity.java

 public void onClick(View arg0) {

  switch(arg0.getId()){

   case R.id.button_1:
     button_1.setActivated(true);
  }
}

推荐答案

这是Android的工作方式.建议您使用onSaveInstance/onRestoreInstance的修复方法是正确的处理方法.之所以需要这样做,是因为您的整个活动都已被销毁并重新创建.那些保存的捆绑包是将活动"状态恢复到之前状态的关键.你可以在这里读更多关于它的内容:保存状态

This is how Android works. You're proposed fix of using onSaveInstance/onRestoreInstance is the proper way to handle it. The reason this is necessary is because your entire Activity is destroyed and recreated. Those saved bundles is key to restoring the state of your Activity to what it was before. You can read more about it here: Saving State

请注意,恢复状态的需求不仅会发生在屏幕方向等配置更改期间发生.当用户背景是您的应用程序,以后又重新打开它时,可能会发生这种情况.还有许多其他情况.使用保存/恢复状态可确保它能够处理所有这些情况并正确地恢复您的活动…在您的情况下,请激活该按钮.

Note, the need for restoring state won't just happen during a config change like screen orientation. It could happen when the user background's your app and later re-opens it. There are many many other situations. Using the save/restore state ensures it'll handle all those cases and restore your Activity correctly...in your case, having that button activated.

这篇关于方向更改上的Android按钮状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆