Android Button State on Orientation Change

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-05 08:33:08

问题


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.

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?

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

Thanks.

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

<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

 public void onClick(View arg0) {

  switch(arg0.getId()){

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

回答1:


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.



来源:https://stackoverflow.com/questions/23875350/android-button-state-on-orientation-change

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