如何在 Java(Android) 上迭代我的 RadioButton 以查找字符串

art*_*s90 0 java android

我正在开发一个小测验应用程序。正确的答案存储在字符串数组中,因此当用户选择其中一个选项(每个选项的单选按钮)时,我会进行字符串比较。

如果答案是错误的,则应该对其他单选按钮进行迭代,以验证哪个单选按钮与我的答案数组具有相同的字符串,以标记这是正确的答案。

correctAnswer = answers[position];
int currentAnswerId = optionsRadioGroup.getCheckedRadioButtonId();
    RadioButton selectedAnswer = (RadioButton) findViewById(currentAnswerId);
    if(selectedAnswer.getText().equals(correctAnswer)) {
                    selectedAnswer.setTextColor(Color.GREEN);
                }
                else {
                    selectedAnswer.setTextColor(Color.RED);
                    //search the other radioButtons for the matching string

                }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,我猜这并不难,但我是 Android 和 Java 开发新手。

vip*_*tal 6

您可以简单地循环遍历无线电组的所有子视图,然后

int count = radioGroup.getChildCount();
        for (int i=0;i<count;i++) {
            View o = radioGroup.getChildAt(i);
            if (o instanceof RadioButton) {
                RadioButton selectedAnswer =(RadioButton)o;
                if(selectedAnswer.getText().equals(correctAnswer)) {
                    selectedAnswer.setTextColor(Color.GREEN);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)