简体   繁体   中英

Android Button State on Orientation Change

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);
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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