android 代码自定义checkbox,android CheckBox简单自定义样式

CheckBox用得比较多,但又不是那么多。有些属性时间长了就忘记了。要玩出花样当然有很多内容可以写。但有时候我们需要简单快速的实现设计需求。至于复杂的实现,比如需要添加动画等,根据需要再进一步进行自定义。本文主要介绍一种简单快捷的实现方式,便于自己进行代码重用。

1. 图标效果

a0f1e6a0d149cc7916fc504e58c50edf.png

f08bb61df121981c7a7bdaff600aea1f.png

2. 代码

界面

android:id="@+id/checkbox_container"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="@dimen/margin_xsmall"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent">

android:id="@+id/checkbox"

android:layout_width="@dimen/checkbox_width"

android:layout_height="@dimen/checkbox_height"

android:background="@drawable/check_box"

android:button="@null"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

主要是禁用了button,而使用background属性来实现变化

代码

checkboxContainer.setOnClickListener {

checkbox.isChecked = checkbox.isChecked.not()

}

checkbox.setOnCheckedChangeListener { _, isChecked ->

//TODO 保存配置选项

}

selector代码

啰嗦一句,selector的规则有点类似于kotlin中的when关键字的用法,从上到下的判断条件,满足了哪个就优先跳出了选择,不满足就进行下一步判断,直到满足。所以一般最后一个都是默认的图片,类似于default.