Android: selector on custom view attribute

I tried to describe this tutorial: How to add a custom button state , create your own view attribute, and use a selector to change its state. I can't seem to get it to work. Button selector works fine on non-standard selectors like button click, but doesn't work for my costum toggle. My code looks like this:

in attrs.xml:

<resources>
    <declare-styleable name="ValueButton">
        <attr name="toggle" format="boolean" />
    </declare-styleable>
</resources>

      

In my custom button class definition file called ValueButton.java:

public class ValueButton extends Button
{
    private static final int[] STATE_TOGLLE = {R.attr.toggle};
    private boolean toggle = false;

    public void setToggle(boolean val)
    {
        toggle = val;
    }

    public ValueButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
        if(toggle)
            mergeDrawableStates(drawableState,STATE_TOGLLE);
        return drawableState;
    }
}

      

In my opinion this uses a button:

<LiniarLayout>
    <com.myapp.ValueButton
            android:id="@+id/rightText"
            custom:toggle="false"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            style="@style/ValueSwitchStyle"
     />
</LiniarLayout>

      

in styles.xml file:

<style name="ValueSwitchStyle">
     <item name="android:background">@drawable/value_switch_background</item>
</style>

      

and finally my background definitions file (button_background.xml) located in the drawables folder:

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/com.myapp.ValueButton">
    <item custom:toggle="true" android:drawable="@color/blue"/>
    <item custom:toggle="false" android:drawable="@color/white"/>
</selector>

      

+3


source to share


1 answer


you missed a call refreshDrawableState

public void setToggle(boolean val) {
        toggle = val;
        refreshDrawableState();
}

      



from documentation

Call this to force the view to update its valid state.

+1


source







All Articles