簡體   English   中英

如何在 Java/Kotlin 中以編程方式對單選按鈕進行分組?

[英]How to group radio buttons programmatically in Java/Kotlin?

我在帶有 ConstraintLayout 的 XML 布局文件中有一個單選按鈕的自定義視圖。 我需要對這些單選按鈕進行分組。 但是當我嘗試用 Radio 組包圍 ConstraintLayout 時,它不會對按鈕進行分組並且所有選項都被選中。

在此處輸入圖像描述

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);
            }
        }
    }
};

您可以在默認運行中設置 false 選中的圖標,就像布局 xml 中的代碼一樣

android:checked="假"

在編碼中你可以

在kotlin中使用如下代碼

radioGroup.check(id)

首先,你寫單選組的名字,然后用單選按鈕的 ID 代替 ID,

比如我的項目中是這樣的

rg_licenseType.check(R.id.rb_three)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM