【问题标题】:How to group radio buttons programmatically in Java/Kotlin?如何在 Java/Kotlin 中以编程方式对单选按钮进行分组?
【发布时间】:2021-11-04 04:09:49
【问题描述】:

我在 XML 布局文件中使用 ConstraintLayout 为单选按钮提供了一个自定义视图。我需要对这些单选按钮进行分组。但是当我尝试用 Radio 组封装 ConstraintLayout 时,它不会对按钮进行分组,并且所有选项都被选中。

【问题讨论】:

  • 为什么不制作自定义视图?您的布局非常漂亮,可以使用普通的旧 RadioGroup 逻辑,并且有很多文章可以让您在广播组中获得“众多”选择功能
  • @gtxtreme 你的意思是说使用旧的 RadioGroup 逻辑无法在此自定义视图中使用单选组吗?
  • 我在 RadioGroup 方面的经验有限,但我知道我们将它用于“众多”选择功能,并且就外观而言,RadioGroup 中的自定义是有限的跨度>
  • bitbucket.org/ManuelMato/customradiobutton/src/develop/app/src 你试过看这个吗?似乎与您的用例类似

标签: android radio-button android-constraintlayout radio-group


【解决方案1】:

RadioButtons 必须是 RadioGroup 的直接子级才能使分组功能起作用。 RadioGroup 只是一个特殊的 LinearLayout,它为所有添加的 RadioButtons 子项实现分组功能。您可以简单地实现自己的分组功能,方法是将 RadioButtons 添加到 List,然后实现 OnCheckedChangeListener 并将其设置在每个 RadioButtons 上,如下所示:

 private final List<RadioButton> radioButtons = new ArrayList<>();
private int checkedId;

private void setRadioButton(RadioButton radioButton) {
    radioButtons.add(radioButton);
    radioButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
}

private final CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
        new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            checkedId = buttonView.getId();
        }

        for (RadioButton radioButton : radioButtons) {
            if (radioButton.getId() != checkedId) {
                radioButton.setChecked(false);
            }
        }
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2011-11-01
    • 2013-06-14
    • 1970-01-01
    • 2013-01-25
    • 2013-06-02
    • 2021-12-19
    相关资源
    最近更新 更多