2013-08-28 21 views
0

我正在扩展“按钮”以创建自定义按钮,我正在为其添加额外的功能 - 目前,背景可绘制在触摸时不会改变。下面是一些示例代码,显示我目前在做什么:在自定义按钮上使用背景可绘制选择器

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

如预期的接触状态工作...

+1

为什么在ctor(Contexr)中调用super(Context,null)并在ctor(Context,AttributeSet)中使用super(Context,AttributeSet,int)? – pskink

+0

将此添加到您的b_gradient_states选择器标记中:xmlns:app =“http://schemas.android.com/apk/res/com.mydomain.mypackage” –

+0

您让我朝着正确的方向pskink ..它只是一个bug ! :) – Garett

回答

0

Pskink在问题中留言说:

为什么在构造函数(Contexr)调用超(上下文,空)和 构造函数(上下文,AttributeSet中)使用超(上下文,AttributeSet中,INT)

而这正是发生了什么事......

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

应该是:

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