android 用ImageButton 实现自定义CheckBox
大家好,我是梦辛工作室的灵,今天来说一下 android的 checkbox,作为选择框我们会经常使用,但是呢android 原生提供的 checkbox就有一些气人了,我们没有办法去控制它的大小,限制了它的大小,结果里面的边框也没有变小或变大,,也不好修改它的样式,这样就不好布局了,所以楼主通常会用到ImageButton来作为CheckBox的代替品
下面楼主来写一个示意
先看效果图:
先准备三个资源文件,一个是background选中的,一个是background未选中的,一个是 src 的,src有时即是选中
在drawable目录下新建
ic_check_box_back_sel.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp" />
<solid android:color="#19C6B2" />
<size android:width="20dp" android:height="20dp" />
</shape>
ic_check_box_back_unsel.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp" />
<solid android:color="#F0F0F0" />
<size android:width="20dp" android:height="20dp" />
</shape>
ic_check_box_center.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="@color/colorWhite" />
<size android:width="10dp" android:height="10dp" />
</shape>
然后就是 ImageButton 的代码:
选中代码:
<ImageButton
android:id="@+id/imgbtn_woman"
android:layout_width="@dimen/white_back_add_imgbtn_width"
android:layout_height="@dimen/white_back_add_imgbtn_height"
android:background="@drawable/ic_check_box_back_sel"
android:src="@drawable/ic_check_box_center"/>
未选中的代码:
<ImageButton
android:id="@+id/imgbtn_woman"
android:layout_width="@dimen/white_back_add_imgbtn_width"
android:layout_height="@dimen/white_back_add_imgbtn_height"
android:background="@drawable/ic_check_box_back_unsel"
android:src="@drawable/ic_check_box_center"/>