sua piuttosto facile :) In primo luogo è necessario creare una classe che CustomCheckBox estenderà CheckBox e sostituisce il metodo 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);
}
}
}
Crea anche il vostro selettore di nome custom_check_box
nella cartella drawable:
<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>
e usare il vostro icone personalizzate/imgs nel XML qui sopra per tutti e tre gli stati (incentrato/premuto/default)
utilizzare il componente personalizzato nel XML come questo:
<*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"/>
e Java:
private CustomCheckBox mCheckbox;
mCheckbox = (CustomCheckBox) findviewbyid(R.id.myCheckbox);
Funziona perché l'ho usato in entrambi i modi :) E con alcune modifiche funziona anche per RadioButton allo stesso modo. Buona programmazione!
Grazie! Ha funzionato perfettamente per me ... –
se voglio deselezionare la voce selezionata quale proprietà del selettore può essere usata .. –
Devo programmare a livello di gen checkbox come posso usare checkbox personalizzato qualcuno ha un'idea? – UmAnusorn