3

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>
1
  • What does the line final int[] drawableState = super.onCreateDrawableState(extraSpace + 2); do? Commented Mar 10, 2021 at 5:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

setToggle is never called in my app, its only there for future code. Your solution doesn't work.
You have to read the custom state from the attrs object you get in the constructor, set the boolean and call refreshDrawableState

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.