它很容易:) 首先,你需要創建一個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
使用您的自定義圖標/ IMGS像這樣在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"/>
and java:
private CustomCheckBox mCheckbox;
mCheckbox = (CustomCheckBox) findviewbyid(R.id.myCheckbox);
它的工作原理是因爲我用它兩種方式:)而且一些調整它也適用於RadioButtons同樣的方式。快樂的編碼!
謝謝!我完全爲我工作... –
如果我想取消選中的項目選擇器的哪個屬性可以使用.. –
我必須以編程方式生成複選框如何使用自定義複選框任何人有一個想法? – UmAnusorn