在自定义按钮上使用背景可绘制选择器



我正在扩展"Button"以创建一个自定义按钮,我正在为其添加额外的功能——目前,后台绘图不会在触摸时发生变化。下面是一些示例代码,显示了我目前正在做的事情:

/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>

**注意**如果我更改

<com.blah.controls.CustomButton...

<Button...

触摸状态按预期工作。。。

Pskink在问题的评论中说:

为什么在ctor(Contexr)中调用super(Context,null)使用super(Context,AttributeSet,int)的ctor(上下文,AttributeSet)

这正是问题所在。。。

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

应该是:

public CustomButton(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }
// 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>

最新更新