Android CheckBox多选、单选、全选、全不选
2019-11-19 本文已影响0人
hao_developer
效果图
微信图片_20191119103005.jpg 微信图片_20191119103016.jpg 微信图片_20191119103021.jpg 微信图片_20191119103026.jpg问题
CheckBox设置isCheck=true,会自动触发监听事件onCheckedChanged,从而导致里面方法会自动执行?
解决方法
可用把全选、全不选的CheckBox通过点击事件来实现选择
/**
* 全选 全不选 部分代码
*/
var isAllChecked = false;//ture:全选 false:全不选
cbAll.setOnClickListener(this)
override fun onClick(v:View?){
when(v?.id){
R.id.cbAll ->{//全选 全不选
isAllChecked = !isAllChecked
if (isAllChecked) {//全选
cbReceivables.isChecked = true
cbActivity.isChecked = true
cbCash.isChecked = true
cbMemManagment.isChecked = true
cbDistribution.isChecked = true
cbStoreOper.isChecked = true
} else {//全不选
cbReceivables.isChecked = false
cbActivity.isChecked = false
cbCash.isChecked = false
cbMemManagment.isChecked = false
cbDistribution.isChecked = false
cbStoreOper.isChecked = false
}
}
}
}
/**
* 单选的操作
*/
cbActivity.setOnCheckedChangeListener(this)
cbCash.setOnCheckedChangeListener(this)
cbMemManagment.setOnCheckedChangeListener(this)
cbDistribution.setOnCheckedChangeListener(this)
cbStoreOper.setOnCheckedChangeListener(this)
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
isAllCheck(isChecked)
}
/**
* 判断是否全选
*/
fun isAllCheck(isChecked: Boolean) {
if (isChecked) {
if (cbReceivables.isChecked && cbActivity.isChecked && cbCash.isChecked
&& cbMemManagment.isChecked && cbDistribution.isChecked && cbStoreOper.isChecked
) {
cbAll.isChecked = true
isAllChecked = true
}
} else {
cbAll.isChecked = false
isAllChecked = false
}
}