简体   繁体   中英

How to select one radio button from dynamically created radio buttons?

I have a situation to select one radio button from dynamically created radio buttons. I know it is possible with Radio group but still I am not able to do it because my situation is little different. Let me explain it.

I have a question like "A recent survey found that in British secondary schools" with 4 options like A.

B.

C.

D.

All data coming from the server in json form. I have created the view dynamically with one question and four options with radio buttons. But what i am understanding is every row is new row and I am not able to select only one radio buttons from all radio buttons. Every button is selecting individually but I want to select only one radio button on which I click.

Any help would be appreciated.

you can see my view below:

在此处输入图片说明

My code is :

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


    }

I have been working on it from a while and finally I find the way how to do it , posting my answer to let others take idea from it. I make it work by taking the array of Textview and Radiogroup outside the inner for loop.

Thank you everyone for the assistance. Happy Coding:)

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

        }


    }

Use RadioGroup as below:

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

Here you can select only one option out of multiple

As you required how to select value, then please use following code snippet:

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.


       }
   }
   );

Thanks

Hello @Sandeep Singh Bandral

You have done a great Work, Why you are doing such a heavy work Just Create a Radio Group Work and assign a Id ,and call setOnCheckedChangeListener

You can see here

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

        }); 

In the place of Toast ,DO YOUR STUFF

Test Case:if you don't know how many radio buttons for each Question, you can see the below code over here

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

I know this is rather old, but I just had the same problem. The solution is to change the state of RadioButton after adding it to RadioGroup by addView(). I guess this is also what BAKUS tried to say by his sample code.

copied from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM