android 用ImageButton 实现自定义CheckBox

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"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灵神翁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值