简体   繁体   中英

Every time orientation change, button state changes

It's work fine when the app starts, no matter what orientation it is, but after changing the orientation, if the button is selected, its became unselected. this is the drawable xml for the button

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">   

<item android:state_selected="true"    
    android:drawable="#fff" />
<item android:state_enabled="false"   
    android:drawable="000" />   
<item android:state_checked="true"    
    android:drawable="#fff" />   
<item android:drawable="#f0f0f0" />   

</selector>  

When an orientation change on your device, your Activity will be destroyed and recreated. You can save and restore the button's state by implementing onSaveInstanceState(Bundle outState) . For more information on the activity's lifecycle and how to use onSaveInstanceState/onRestoreInstanceState check out this article .

You can write the button's state as a boolean using isSelected . For example in your activity you can do the following:

public static final String BUTTON_STATE = "buttonState";

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(BUTTON_STATE, button.isSelected());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

To restore your button's state you can do this:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    button.setSelected(savedInstanceState.getBoolean(BUTTON_STATE));
}

Here's an additional resource on how to save state with Fragments.

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