扩大AppCompatCheckBox点击区域(点击外部ViewGroup,内部AppCompatCheckBox选中状态切换)

本文介绍了如何扩大AppCompatCheckBox的点击区域,使得点击其外层ViewGroup时,内部的AppCompatCheckBox能正确切换选中状态。由于子View仅在视觉上继承了父View的状态,因此AppCompatCheckBox自身无法正确感知选中变化。解决方案包括使用CheckableLinearLayout来判断选中状态,或监听CheckableLinearLayout的点击事件手动更新AppCompatCheckBox状态。
摘要由CSDN通过智能技术生成
    <com.demo.CheckableLinearLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#00ff00"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.AppCompatCheckBox
            android:id="@+id/checkbox_favourite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:duplicateParentState="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#ff0000"
            android:text="收藏"
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Kotlin 中,可以通过使用 AppCompatCheckBox 和 RadioGroup 来实现单选效果。具体步骤如下: 1. 在布局文件中添加一个 RadioGroup 和多个 AppCompatCheckBox,如下所示: ``` <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.appcompat.widget.AppCompatCheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项1"/> <androidx.appcompat.widget.AppCompatCheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项2"/> <androidx.appcompat.widget.AppCompatCheckBox android:id="@+id/checkBox3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项3"/> </RadioGroup> ``` 2. 在 Kotlin 代码中设置 RadioGroup 的监听器,并在监听器中处理单选逻辑,代码如下: ``` val radioGroup = findViewById<RadioGroup>(R.id.radioGroup) val checkBox1 = findViewById<AppCompatCheckBox>(R.id.checkBox1) val checkBox2 = findViewById<AppCompatCheckBox>(R.id.checkBox2) val checkBox3 = findViewById<AppCompatCheckBox>(R.id.checkBox3) radioGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.checkBox1 -> { checkBox1.isChecked = true checkBox2.isChecked = false checkBox3.isChecked = false } R.id.checkBox2 -> { checkBox1.isChecked = false checkBox2.isChecked = true checkBox3.isChecked = false } R.id.checkBox3 -> { checkBox1.isChecked = false checkBox2.isChecked = false checkBox3.isChecked = true } } } ``` 在监听器中使用 when 表达式判断选中的是哪个 AppCompatCheckBox,然后根据选中的情况设置 AppCompatCheckBox 的 isChecked 属性。这样就可以实现单选效果了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值