簡體   English   中英

android 第一個單選按鈕在 radiogroup 中保持選中狀態

[英]android first radiobutton remain checked in radiogroup

我正在開發我的第一個 Android Studio 應用程序,我遇到了無法解決的單選按鈕問題。 我的應用程序是一種多項選擇測驗,當我檢查第一個單選組中的第一個單選按鈕時,即使我檢查同一個單選組的另一個單選按鈕,它仍然處於選中狀態,在這種情況下,我同時檢查了兩個單選按鈕時間如下圖所示。

在此處輸入圖像描述

但是,其他無線電組工作正常。 單選按鈕和組以編程方式創建,如下所示:

 LinearLayout layoutQuiz = findViewById(R.id.layoutQuiz);
 for (int i = 1; i < 5; i++) {
      RadioGroup radioGroup = new RadioGroup(this);
      radioGroup.setId(i);
      TextView text = new TextView(this);
      text.setText(i + ") Question text?");
      layoutQuiz.addView(text);
            
      for (int j = 1; j < 4; j++) {
           RadioButton answer = new RadioButton(this);
           answer.setId(j);
           answer.setText("answer nr" + j);
           radioGroup.addView(answer);
      }
      layoutQuiz.addView(radioGroup);

      radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
        //do something
      });
 }

我該如何解決? 提前致謝。

當您使用 setId() 檢查此答案時,我相信LinearLayout中的 ID 之間存在沖突

我測試了你的代碼,它使用了 RadioGroup 的更高 ID

 LinearLayout layoutQuiz = findViewById(R.id.layoutQuiz);
        for (int i = 1; i < 5; i++) {
            RadioGroup radioGroup = new RadioGroup(this);
            radioGroup.setId(i*1000); // i make chenge only on this line
            TextView text = new TextView(this);
            text.setText(i + ") Question text?");
            layoutQuiz.addView(text);

            for (int j = 1; j < 4; j++) {
                RadioButton answer = new RadioButton(this);
                answer.setId(j);
                answer.setText("answer nr" + j*i);
                radioGroup.addView(answer);

            }
            layoutQuiz.addView(radioGroup);

            radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
                //do something
            });
        }
            /*
            rest of your code
             */

更新

正如@Mnih Ngo 建議的那樣,在以編程方式設置時使用View.generateViewId ()來避免 ID 沖突

radioGroup.setId(View.generateViewId());

嗨,請檢查此解決方案,希望它會起作用。

LinearLayout layoutQuiz = findViewById(R.id.layoutQuiz);
 int selectedItem;

for (int i = 1; i < 5; i++) {
  RadioGroup radioGroup = new RadioGroup(this);
  radioGroup.setId(i);
  TextView text = new TextView(this);
  text.setText(i + ") Question text?");
  layoutQuiz.addView(text);
        
  for (int j = 1; j < 4; j++) {
       RadioButton answer = new RadioButton(this);
       answer.setId(j);
       answer.setText("answer nr" + j);
      answer.setChecked(i == selectedItem); // Only select button with same index 
       radioGroup.addView(answer);
  }
  layoutQuiz.addView(radioGroup);

  radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    //do something
    selectedItem=checkedId;//here set the id
  });
}

暫無
暫無

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

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