Using a background drawable selector on custom button

[亡魂溺海] 提交于 2019-12-12 04:35:33

问题


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>


来源:https://stackoverflow.com/questions/18498606/using-a-background-drawable-selector-on-custom-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!