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

时间:2016-09-22 05:59:34

标签: android radio-button

我有从动态创建的单选按钮中选择一个单选按钮的情况。我知道这对Radio组来说是可能的,但我仍然无法做到,因为我的情况有所不同。让我解释一下。

我有一个像#34的问题;最近的一项调查发现,在英国的中学和#34;有4个选项 甲

下进行。

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


    }

4 个答案:

答案 0 :(得分:2)

我从一段时间以来一直在努力,最后我找到了如何做到的方式,发布我的答案,让其他人从中获取想法。我通过在内部for循环外部采用Textview和Radiogroup数组来实现它。

谢谢大家的帮助。快乐编码:)

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 :(得分: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.


       }
   }
   );

由于

答案 2 :(得分:0)

你好@Sandeep Singh Bandral

你做了很棒的工作,为什么要做这么繁重的工作 只需创建一个广播组工作并分配一个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; 
                   } 
              } 
         } 
    }); 

答案 3 :(得分:0)

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

复制自 here