如何从动态创建的单选按钮中选择一个单选按钮?

4
我有一个情况需要从动态创建的单选按钮中选择一个。我知道使用Radio group是可能的,但由于我的情况有些不同,我仍然无法做到。让我解释一下。
我有一个问题:“最近的调查发现,在英国的中学中”,有4个选项,如 A。 B。 C。 D。
所有数据都以json形式从服务器传输。我已经动态创建了一个包含一个问题和四个带单选按钮的选项的视图。但我理解的是每一行都是新行,我无法只从所有单选按钮中选择一个单选按钮。每个按钮都是单独选择的,但我想要在我点击的单选按钮上选择一个单选按钮。
任何帮助将不胜感激。
您可以在下面看到我的视图:

enter image description here

我的代码是:

    LinearLayout linearLayoutForQuestions = (LinearLayout)   view.findViewById(R.id.questionsLinearLayout);
    linearLayoutForQuestions.removeAllViews();

    //set the questions for the user

    for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {

        final List<String> list = new ArrayList();
        list.add("SELECT");
        TextView textView = new TextView(activity);
        textView.setTextSize(15);
        textView.setTextColor(view.getResources().getColor(R.color.black));
        textView.setTypeface(typeface1);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 20, 0, 0);
        textView.setLayoutParams(params);

        String question = totalNoOfQuestions.get(ss).getQuestions();
        String questionNo = totalNoOfQuestions.get(ss).QuestionNo;
        textView.setText("Question " + questionNo + " " + question);

        //linearlayout and set data inside it
        LinearLayout parent = new LinearLayout(activity);
        parent.removeAllViews();
        parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        parent.setOrientation(LinearLayout.VERTICAL);


        int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
        for (int s = 0; s < optionSize; s++) {


            //children of parent linearlayout
            LinearLayout layout2 = new LinearLayout(activity);
            layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            layout2.setOrientation(LinearLayout.HORIZONTAL);
            layout2.setGravity(Gravity.CENTER);

            String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
            TextView textView1 = new TextView(activity);
            textView1.setText(optionNo);
            textView.setTextSize(15);

            final RadioButton radioButton = new RadioButton(activity.getApplicationContext());
            radioButton.setId(s);
            radioButton.setBackgroundResource(R.drawable.settings_background_ripple);
            LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            pa.setMargins(10,10,10,10);
            radioButton.setLayoutParams(pa);


            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int checkedRadioButtonId = buttonView.getId();
                    Toast.makeText(activity, "hit it", Toast.LENGTH_SHORT).show();
                }
            });

            String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
            TextView textView2 = new TextView(activity);
            textView2.setTextSize(15);
            textView2.setText(questionOption);

            layout2.addView(textView1);
            layout2.addView(radioButton);
            layout2.addView(textView2);

            parent.addView(layout2);

        }

        linearLayoutForQuestions.addView(textView);
        linearLayoutForQuestions.addView(parent);


    }

你需要在RadioGroup中添加单选按钮。 - D.J
在 for 循环之前创建一个 RadioGroup,并在 for 循环中添加单选按钮。 - D.J
好的,我会尝试一下。你有任何可用的演示吗?我也尝试了单选按钮组,但是没有得到任何帮助。 - Sandeep Singh
4个回答

2

我已经在这个问题上工作了一段时间,最终找到了解决方法,并在此发布我的答案,以便其他人可以从中获得启发。我通过将Textview和Radiogroup数组移到内部for循环之外来使其正常工作。

感谢大家的帮助,祝编码愉快 :)

LinearLayout linearLayoutForQuestions = (LinearLayout) view.findViewById(R.id.questionsLinearLayout);
    linearLayoutForQuestions.removeAllViews();

    totalNoOfQuestions = readingTests[countReadingTest].getQuestion();



    //set the questions for the user
    for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {

        groupNo = ss;
        final List<String> list = new ArrayList();
        list.add("SELECT");
        TextView textView = new TextView(activity);
        textView.setTextSize(15);
        textView.setTextColor(view.getResources().getColor(R.color.black));
        textView.setTypeface(typeface1);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 20, 0, 0);
        textView.setLayoutParams(params);

        String question = totalNoOfQuestions.get(ss).getQuestions();
        String questionNum = totalNoOfQuestions.get(ss).QuestionNo;
        textView.setText("Question " + questionNum + " " + question);

        //linearlayout and set data inside it
        LinearLayout parent = new LinearLayout(activity);
        parent.removeAllViews();
        parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        parent.setOrientation(LinearLayout.VERTICAL);

        final int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
        final RadioButton[] radioButton = new RadioButton[optionSize];
        int size = totalNoOfQuestions.size();
        final RadioGroup[] radioGroup = new RadioGroup[size]; //you can also create in xml
        radioGroup[ss] = new RadioGroup(activity);
        radioGroup[ss].setId(ss + 100);
        radioGroup[ss].setOrientation(RadioGroup.VERTICAL)ø;

        //this textview is for the optionsNo like A,B,C,D
        final TextView[] textView1 = new TextView[optionSize];

        LinearLayout layoutOptionsNo = new LinearLayout(activity);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        layoutOptionsNo.setOrientation(LinearLayout.VERTICAL);
        layoutOptionsNo.setWeightSum(optionSize);
        layoutOptionsNo.setGravity(Gravity.CENTER);
        layoutOptionsNo.setPadding(10, 0, 0, 0);
        layoutOptionsNo.setLayoutParams(layoutParams);


        LinearLayout layoutOptions = new LinearLayout(activity);
        layoutOptions.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
        layoutOptions.setOrientation(LinearLayout.HORIZONTAL);
        layoutOptions.setWeightSum(4);
        layoutOptions.setGravity(Gravity.CENTER);

        //inner loop for the options for every single question
        for (int s = 0; s < optionSize; s++) {

            String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
            textView1[s] = new TextView(activity);
            textView1[s].setText(optionNo);
            textView1[s].setTextSize(15);
            textView1[s].setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            pa.setMargins(10, 10, 10, 10);
            pa.weight = 1;
            textView1[s].setLayoutParams(pa);

            String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
            radioButton[s] = new RadioButton(activity);
            radioButton[s].setId(s);
            radioButton[s].setText(questionOption);
            radioButton[s].setTextSize(15);
            radioButton[s].setPadding(2, 2, 2, 2);
            radioButton[s].setBackgroundResource(R.drawable.settings_background_ripple);

            LinearLayout.LayoutParams pa2 = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
            pa2.setMargins(10, 10, 10, 10);
            pa2.weight = 1;
            radioGroup[ss].setLayoutParams(pa2);
            radioGroup[ss].addView(radioButton[s]);
            layoutOptionsNo.addView(textView1[s]);


        }

        radioGroup[ss].setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int originalId ;
                int id = group.getId();{
                     originalId = id-100;
                }
                questionNo = totalNoOfQuestions.get(originalId).getQuestionNo();
                optionNo = totalNoOfQuestions.get(0).getOptions().get(checkedId).getQuestionOptionNo();

            }
        });

        layoutOptions.addView(layoutOptionsNo);
        layoutOptions.addView(radioGroup[ss]);
        parent.addView(layoutOptions);

        linearLayoutForQuestions.addView(textView);
        linearLayoutForQuestions.addView(parent);

    }
    boolean showOptionHint = totalNoOfQuestions.get(0).OptionList;
    LinearLayout linearLayoutForOptions = (LinearLayout) view.findViewById(R.id.optionsLinearLayout);
    linearLayoutForOptions.removeAllViews();
    if (showOptionHint == true) {
        //dynamic creation of options under the quesiton layout
        List<ReadingTest.QuestionBean.OptionsBean> questionOptions = readingTests[countReadingTest].getQuestion().get(0).getOptions();
        for (int ss = 0; ss < questionOptions.size(); ss++) {
            String options = questionOptions.get(ss).getQuestionOption();
            String optionsNo = questionOptions.get(ss).getQuestionOptionNo();
            TextView textView = new TextView(activity);
            textView.setTextSize(18);
            textView.setTypeface(typeface);
            textView.setTextColor(view.getResources().getColor(R.color.black));
            textView.setText(optionsNo + ". " + options);
            linearLayoutForOptions.addView(textView);

        }


    }

1
使用以下代码中的RadioGroup
      LinearLayout layout = (LinearLayout) findViewById(R.id.layout); //layout defined in xml main activity layout

                    RadioGroup radioGroup = new RadioGroup(this); //you can also create in xml

                    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.FILL_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                    );
                    layout.addView(radioGroup, p);

 /*radio button 1*/

                    RadioButton radioButtonView1 = new RadioButton(this);
                    radioButtonView1.setText("RadioButton1");
                    radioButtonView1.setOnClickListener(this);
                    radioGroup.addView(radioButtonView1, p);
/*radio button 2*/
                    RadioButton radioButtonView2 = new RadioButton(this);
                    radioButtonView2.setText("RadioButton2");
                   radioButtonView2.setOnClickListener(mThisButtonListener);    
                    radioGroup.addView(radioButtonView2, p);
/*radio button 3*/
                    RadioButton radioButtonView3 = new RadioButton(this);
                    radioButtonView3.setText("RadioButton3");
                   radioButtonView3.setOnClickListener(mThisButtonListener);
                    radioGroup.addView(radioButtonView3 , p);
/*radio button 4*/
                    RadioButton radioButtonView4 = new RadioButton(this);
                    radioButtonView4 .setText("RadioButton4");
                   radioButtonView4.setOnClickListener(mThisButtonListener);
                    radioGroup.addView(radioButtonView4 , p);

在这里,您可以从多个选项中选择一个选项

根据您的要求如何选择值,请使用以下代码片段:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId)
       {
           radioButton = (RadioButton) findViewById(checkedId);
           Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show(); //text related to option selected.


       }
   }
   );

谢谢


这个适用于只有一行的情况,但在我的情况下,我有多行,每行都有一个单选按钮。 - Sandeep Singh
还没有,其实你是对的,但我觉得我无法恰当地解释我的情况。 - Sandeep Singh
如果您看到我的代码,两个for循环同时运行。一个是用于总问题数的,而内部的for循环则用于特定问题的选项,这在我的情况下为4。现在真正的问题是我们需要在内部for循环中初始化radiogroup,否则它会显示一个错误“child has already parent please remove it”,类似于这样的东西,但这会使radiogroup成为每一行的单独单选按钮组,这在我的情况下是选项。我希望您能理解我的观点。 - Sandeep Singh
我已经在这个情况中卡了几天了,一直在持续地工作,但目前无法找到任何解决方案。 - Sandeep Singh
你还遇到问题吗?对于你的旧问题,你应该改善你的视图层次结构。 - Androider
暂时不需要,谢谢。是的,你说得对,我改变了我的视图层次结构,它起作用了,我也在下面发布了我的答案。 - Sandeep Singh

0

我知道这可能有些过时,但我刚遇到了同样的问题。解决方法是在将RadioButton添加到RadioGroup中后通过addView()改变其状态。我想这也是BAKUS在他的示例代码中试图表达的。

摘自这里


0
你好@Sandeep Singh Bandral
你做得非常好,为什么要做这样的繁重工作呢? 只需创建一个 Radio Group 工作并分配一个 Id,并调用 setOnCheckedChangeListener 函数即可。
你可以在这里看到。
 radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override 
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // find which radio button is selected 
                if(checkedId == R.id.answer1) {
                    Toast.makeText(getApplicationContext(), "Answer1", 
                            Toast.LENGTH_SHORT).show();
                } else if(checkedId == R.id.answer2) {
                    Toast.makeText(getApplicationContext(), "Answer2", 
                            Toast.LENGTH_SHORT).show();
                }else if(checkedId == R.id.answer3) {
                    Toast.makeText(getApplicationContext(), "Answer3", 
                            Toast.LENGTH_SHORT).show();
                }  else { 
                    Toast.makeText(getApplicationContext(), "Answer4", 
                            Toast.LENGTH_SHORT).show();
                } 
            } 

        }); 

在 Toast 的位置,做你的事情

测试用例:如果您不知道每个问题有多少单选按钮,可以在此处查看下面的代码

radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
         void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
              for(int i=0; i<radioGroup.getChildCount(); i++) {
                   RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
                   if(btn.getId() == checkedId) {
                        String text = btn.getText();
                        // do something with text 
                        return; 
                   } 
              } 
         } 
    }); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接