简体   繁体   English

方向更改上的Android按钮状态

[英]Android Button State on Orientation Change

I have a problem keeping the state of my buttons - say Button1.setActivated(true) . 我在保持按钮状态时遇到问题-说Button1.setActivated(true) When orientation is changed this is forgotten and it is not reactivated or shown as activated. 更改方向后,该位置将被忘记,并且不会重新激活或显示为已激活。

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. 我想我可以使用IF来测试Button状态的状态,将其存储在变量中,然后使用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? 当然会有更好的方法吗?

I'm still pretty new to Android so I could be missing something obvious. 我对Android还是很陌生,所以我可能会遗漏一些明显的东西。

Thanks. 谢谢。

Update: The setActivated changes the background colour of the button using a selector. 更新:setActivated使用选择器更改按钮的背景颜色。 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);
  }
}

This is how Android works. 这就是Android的工作方式。 You're proposed fix of using onSaveInstance/onRestoreInstance is the proper way to handle it. 建议您使用onSaveInstance / onRestoreInstance的修复方法是正确的处理方法。 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. 使用保存/恢复状态可确保它能够处理所有这些情况并正确激活您的活动……就您而言,激活该按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM