很简单:)
首先,您需要创建一个 CustomCheckBox 类,该类将扩展 CheckBox 并覆盖 onDraw(Canvas canvas) 方法:
public class CustomCheckBox extends CheckBox {
private final Drawable buttonDrawable;
public CustomCheckBox(Context context, AttributeSet set) {
super(context, set);
buttonDrawable = getResources().getDrawable(R.drawable.custom_check_box);
try {
setButtonDrawable(android.R.color.transparent);
} catch (Exception e) {
// DO NOTHING
}
setPadding(10, 5, 50, 5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
buttonDrawable.setState(getDrawableState());
final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
final int height = buttonDrawable.getIntrinsicHeight();
if (buttonDrawable != null) {
int y = 0;
switch (verticalGravity) {
case Gravity.BOTTOM:
y = getHeight() - height;
break;
case Gravity.CENTER_VERTICAL:
y = (getHeight() - height) / 2;
break;
}
int buttonWidth = buttonDrawable.getIntrinsicWidth();
int buttonLeft = getWidth() - buttonWidth - 5;
buttonDrawable.setBounds(buttonLeft, y, buttonLeft + buttonWidth, y + height);
buttonDrawable.draw(canvas);
}
}
}
同时在您的可绘制文件夹中创建名为 custom_check_box 的选择器:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_check_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_check_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_check_on" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_check_off" />
<item android:state_checked="false" android:drawable="@drawable/btn_check_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_check_on" />
</selector>
并在上面的 XML 中为所有三种状态(聚焦/按下/默认)使用您的自定义图标/图像
像这样在您的 XML 中使用自定义组件:
<*package + class path*.CustomCheckBox // example com.mypackage.ui.CustomCheckBox if your project is named "mypackage" and the class is in the "ui" folder
android:text="@string/text"
android:checked="false" android:layout_width="fill_parent"
android:id="@+id/myCheckbox" android:layout_height="wrap_content"/>
和java:
private CustomCheckBox mCheckbox;
mCheckbox = (CustomCheckBox) findviewbyid(R.id.myCheckbox);
它之所以有效,是因为我两种方式都使用它 :) 并且通过一些调整,它也适用于 RadioButtons。编码愉快!