Android : Drawable selector not updated when using back stack (fragment)

390 views Asked by At

I have some troubles with ToggleButtons in one of my Fragment. I have a main activity where I load some fragments which I add to BackStack.

In one of those fragments I have a listview with 3 ToggleButtons on top of it. These buttons have a drawable background :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:shape="oval">
            <solid android:color="@color/greenbutton" />
            <stroke android:width="4dp" android:color="@color/actionBlueLight"/>
        </shape>
    </item>
    <item android:state_checked="false">
        <shape android:shape="oval">
            <solid android:color="@color/greenbutton" />
        </shape>
    </item>
</selector>

When I push one of these buttons I filter my ListView. And I can select an item in my List which will start another fragment (added to back stack too).

My problem is when I push the back button and go back to the fragment with my ListView, the button's background is not updated. I mean that I put in my fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) {
    ...
    Log.d(TAG,"Green = "+buttonGreen.isChecked());
    Log.d(TAG,"Orange = "+buttonOrange.isChecked());
    Log.d(TAG,"Red = "+buttonRed.isChecked());
    ...
 }

All buttons seems unchecked (coming from isChecked()) but the button which was checked before I switch to another fragment still have the background corresponding to state_checked="true".

I tried invalidate() buttons to refresh them in onCreateView but it doesn't do anything.

1

There are 1 answers

0
VincentD On BEST ANSWER

Well , I finally manage to fix my problem by forcing uncheck of the ToggleButtons in onStop() method of my Fragment. This way I'm sure that when fragment will be realoaded after popBackStack(), the default background can't be the one associated to state_checked="true".

public void onStop () {
    buttonGreen.setChecked(false);
    buttonOrange.setChecked(false);
    buttonRed.setChecked(false);

    super.onStop();
}

It looks like a workaround and I would appreciate understand why button state appears as "unchecked" in onCreateView() whereas the drawable visible is the one for "checked" buttons.