在使用自定义按钮背景绘制选择 [英] Using a background drawable selector on custom button

查看:219
本文介绍了在使用自定义按钮背景绘制选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我扩展按钮来创建一个我添加额外的功能自定义按钮 - 目前,背景绘制是不会改变的联系。下面是一些示例code,显示目前我正在做什么:

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

&LT; com.blah.controls.CustomButton ...

&LT;按钮...

触摸状态如预期...

the touch states work as expected...

推荐答案

Pskink在问题评论说:

Pskink said in a comment in the question:

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

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);
    }

应该是:

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

这篇关于在使用自定义按钮背景绘制选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆