安卓自带的CheckBox有时候不能满足项目需求,这时候就需要自己定制一套样式出来。具体实现方法如下:
第一:首先需要找几张自己想要定义成的图片:
把上面的图片放到drawable-xhdpi或者mipmap目录下。
第二:在res目录下面创建drawable文件夹,drawable下面创建xml文件checkbox_selector.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false"
android:state_pressed="true"
android:drawable="@drawable/grid_check_off_press"></item>
<item android:state_checked="false"
android:drawable="@drawable/grid_check_off"></item>
<item android:state_checked="true"
android:state_pressed="true"
android:drawable="@drawable/grid_check_on_press" />
<item android:state_checked="true"
android:drawable="@drawable/grid_check_on"></item>
</selector>
到这里工作已经完成1/2了。
第三:在stytle文件中新建样式:
<style name="mycheckbox" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:button">@drawable/checkbox_selectors</item>
<item name="android:paddingLeft">10.0dip</item>
<item name="android:height">35.0dip</item>
</style>
第四:在布局中使用就好啦,引入stytle样式。
<CheckBox
android:id="@+id/checkBox1"
style="@style/mycheckbox"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignLeft="@+id/tv"
android:layout_below="@+id/tv"
android:layout_marginTop="84dp"
android:text="自定义样式" />