Using a background drawable selector on custom but

2019-08-22 03:52发布

问题:

I am extending "Button" to create a custom button which I am adding extra functionality to -- and currently, the background drawable is not changing on touch. Here is some sample code that shows what I am currently doing:

/src/CustomButton.java

public class CustomButton extends Button {

    public CustomButton(final Context context) {
        this(context, null);
    }

    public CustomButton(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomButton(final Context context, final AttributeSet attrs,
            final int defStyle) {

        super(context, attrs, defStyle);

    }

}

/res/layout/MyView.xml

<com.blah.controls.CustomButton
            android:layout_width="0dp" 
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/b_gradient_states"
            android:text="Button" />

/res/drawable/b_gradient_states

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/b_gradient_pressed"
        android:state_pressed="true" />
    <item
        android:drawable="@drawable/b_gradient"
        android:state_pressed="false" />

</selector>

** Note **If I change

<com.blah.controls.CustomButton...

to

<Button...

the touch states work as expected...

回答1:

Pskink said in a comment in the question:

why in ctor(Contexr) you call super(Context, null) and in ctor(Context, AttributeSet) you use super(Context, AttributeSet, int)

And that's exactly what was wrong...

public CustomButton(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

should be:

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


回答2:

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

    <item android:drawable="@drawable/b_gradient_pressed" android:state_pressed="true"></item>
    <item android:drawable="@drawable/b_gradient_pressed" android:state_focused="true"></item>
    <item android:drawable="@drawable/b_gradient" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
    <item android:drawable="@drawable/b_gradient_pressed" android:state_enabled="false"></item>

</selector>