我扩展了Button小部件,以便能够应用多个自定义属性 .
其中一个属性是我在创建按钮时尝试应用于其背景的滤镜 . 这是行不通的 . (参见下面的屏幕截图和代码)
我尝试在相同的代码位置直接设置背景颜色,它确实改变了背景颜色,但它不是我需要的,因为我使用自己的按钮PNG .
到目前为止有2个问题:
未应用滤色器
自定义按钮已偏移,剪裁且无法单击
第二个按钮使用普通按钮,它按预期定位,可以点击 . 第二个屏幕截图显示确实选择了正确的颜色,并且可以更改代码中该点的按钮背景颜色 .
码:
public class MyButton extends Button {
private int backGroundColor;
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyButton,
defStyle,
0);
try {
Resources res = getResources();
switch( a.getInteger(R.styleable.MyButton_type, 0) ) {
case 0:
backGroundColor = res.getColor(R.color.Black); break;
case 1:
backGroundColor = res.getColor(R.color.Red); break;
case 2:
backGroundColor = res.getColor(R.color.DimGray); break;
}
getBackground().setColorFilter(backGroundColor, Mode.MULTIPLY);
//setBackgroundColor(backGroundColor)
} finally {
a.recycle();
}
}
public MyButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyButton(Context context) {
this(context, null, 0);
}
}
我使用的XML:
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/btn1"
android:text="BTN1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="14sp"
android:textColor="@color/Blue"
android:padding="2dp"
android:layout_margin="4dp"
android:background="@drawable/key_selector"
app:type="RedButton"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="14sp"
android:textColor="@color/Blue"
android:padding="2dp"
android:layout_margin="4dp"
android:background="@drawable/key_selector"
android:id="@+id/btn2"
android:text="BTN2"/>
setColorFilter()结果
的屏幕截图
setBackgroundColor()的截图结果
EDIT 这是我用于普通和按下状态的选择器XML .
android:drawable="@drawable/key1_pressed"
android:state_pressed="true"/>
android:drawable="@drawable/key1"/>