bjar-bjar
bjar-bjar

Reputation: 707

Android: Selector on custom View Attribute

I have tried to folow this guide: How to add a custom button state, to create my own view attribute, and using an selector to change its state. I can't seem to get it to work. The selector for button works fine on non-custom selectors, such as button pressed, but doesn't work for my costum selector. My code is as follows:

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 view that uses the 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 my 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>

Upvotes: 3

Views: 3918

Answers (1)

Blackbelt
Blackbelt

Reputation: 157467

you missed the refreshDrawableState call

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

from the documentation

Call this to force a view to update its drawable state.

Upvotes: 1

Related Questions