【问题标题】:Checkbox parent child relationship android复选框父子关系android
【发布时间】:2020-06-11 13:24:10
【问题描述】:

我想根据https://material.io/components/selection-controls#checkboxes 中给出的材料设计指南在 Android 中为 Checkbox 创建父子关系。

我想要一个父复选框,在它下面会有子复选框,当父复选框被选中时,所有子复选框都会被选中。

如果父复选框未选中,则所有子复选框均未选中。

如果选中了部分(但不是全部)子复选框,则父复选框将变为不确定的复选框。

我检查了开发人员文档https://developer.android.com/guide/topics/ui/controls/checkbox,但没有关于此的信息。

另外,我查看了材料设计文档https://material.io/develop/android/components/checkbox/,他们给出了做同样事情的指南,但是,他们没有给出任何示例项目来做同样的事情。

我尝试使用嵌套创建带有复选框的父子关系,但没有奏效。有没有人知道如何实现这个?

【问题讨论】:

    标签: android checkbox parent-child


    【解决方案1】:

    您需要在“父”复选框上设置一个侦听器,以便在“父”复选框的状态发生变化时切换“子”复选框。

    请参见此处设置监听器: https://developer.android.com/reference/android/widget/CompoundButton#setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener)

    这是一个例子:

        val childCheckBoxes = listOf(checkBox1, checkBox2, checkBox3)
        parentCheckBox.setOnCheckedChangeListener { _, isChecked ->
            childCheckBoxes.forEach {
                it.isChecked = isChecked
            }
        }
    

    同时,听起来您需要为每个子 CheckBox 添加侦听器,以更新父 CheckBox 状态 - 这样,如果选中了任何子 CheckBox,则父 CheckBox 也会被选中。请记住,如果您致电 parentCheckBox.isChecked = true 它还会调用parentCheckBox 的OnCheckedChangeListener,你最终会得到无限递归。因此,在像这样设置isChecked 时,您可能希望禁用 OnCheckedChangeListener。可能看起来像这样:

    val theRealListener = { _, isChecked ->
            childCheckBoxes.forEach {
                it.isChecked = isChecked
            }
        }
    parentCheckBox.setOnCheckedChangeListener(null)
    parentCheckBox.isChecked = whatever
    parentCheckBox.setOnCheckedChangeListener(theRealListener)
    

    “不确定”状态不包含在默认的 Android CheckBox 中 - 它只能是“选中”或“未选中”。您将需要为此使用自定义的东西。也许这个库对你有用: https://github.com/sevar83/indeterminate-checkbox

    如果您决定使用这个库,看起来您需要使用 setOnStateChangedListener 而不是 setOnCheckedChangeListener,但想法保持不变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多