android.widget.RadioGroup无法转换为android.widget.RadioButton [英] android.widget.RadioGroup cannot be cast to android.widget.RadioButton

查看:313
本文介绍了android.widget.RadioGroup无法转换为android.widget.RadioButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际创建了5个单选组,每个组有4个单选按钮.当我尝试使用checkedRadioButton时,模拟器崩溃了?错误是:android.widget.RadioGroup cannot be cast to android.widget.RadioButton.我错了吗? 这是我的代码:

I've created pragmatically 5 radio groups with 4 radio buttons each. When i am trying to use checkedRadioButton the emulator crushes? The error is: android.widget.RadioGroup cannot be cast to android.widget.RadioButton. Were am i wrong? Here is my code:

    radioGroup = new RadioGroup[5];
    answer = new RadioButton[4];
    int i = 0;
    for (Question qn : questions) {
        radioGroup[i] = new RadioGroup(this);
        radioGroup[i].setId(i);
        int j = 0;
        for (Answer an : answers) {
            if (qn.getID() == an.getQuestion_id_answer()) {
                answer[j] = new RadioButton(this);
                answer[j].setText(an.getAnswer());
                answer[j].setId(j);
                radioGroup[i].addView(answer[j]);

                answer[j].setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int checkedRadioButtonId = v.getId();
                        Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
                        RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
                    }
                });
                j++;
            }
        }
        linearLayout.addView(radioGroup[i]);
        i++;
    }

谢谢!

推荐答案

您将通过

radioGroup[i].setId(i);

分别

answer[j].setId(j);

由于i的某些值也可以是j的值(例如i = j = 0),因此有时您会为同一ID分配两次.

Because some values of the i's can also be values for the j's (e.g. i=j=0), you sometimes assign the same id twice.

方法findViewById()将返回具有匹配ID的任何View,只有将其强制转换为相应的类之后,返回的View.

The method findViewById() will return any View with matching id, the returned View is only after that cast to the appropriate class.

现在不小心出现在行中

RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);

首先找到具有请求ID'checkedRadioButtonId'的

RadioGroup.这会导致崩溃.

the RadioGroup with the requested id 'checkedRadioButtonId' is found first. This causes the crash.

要解决此问题,请使用tag属性,例如

To solve the problem, use the tag attribute, for example

radioGroup[i].setTag("rg" + i);answer[j].setTag("rb" + j);

然后您可以通过编写获得带有标签"xyz"的个人View

Then you can get the individual View with tag "xyz" by writing

RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");

这篇关于android.widget.RadioGroup无法转换为android.widget.RadioButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆