簡體   English   中英

如何從動態創建的單選按鈕中選擇一個單選按鈕?

[英]How to select one radio button from dynamically created radio buttons?

我有一種情況可以從動態創建的單選按鈕中選擇一個單選按鈕。 我知道 Radio 組是可能的,但我仍然無法做到,因為我的情況幾乎沒有什么不同。 讓我解釋一下。

我有一個類似“最近的一項調查發現,在英國中學中”這樣的問題,有 4 個選項,例如 A。

B.

C.

D.

來自服務器的所有數據都以 json 形式出現。 我用一個問題和四個帶單選按鈕的選項動態創建了視圖。 但我的理解是每一行都是新行,我無法從所有單選按鈕中只選擇一個單選按鈕。 每個按鈕都是單獨選擇的,但我只想選擇一個我單擊的單選按鈕。

任何幫助將不勝感激。

你可以在下面看到我的觀點:

在此處輸入圖片說明

我的代碼是:

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


    }

我一直在研究它一段時間,最后我找到了如何做到這一點,發布我的答案讓其他人從中汲取靈感。 我通過在內部 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);

        }


    }

使用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 Bandral

您已經完成了一項偉大的工作,為什么您要做如此繁重的工作 只需創建一個 Radio Group Work 並分配一個 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();
                } 
            } 

        }); 

代替吐司,做你的事

測試用例:如果你不知道每個問題有多少個單選按鈕,你可以在這里看到下面的代碼

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

我知道這已經很老了,但我遇到了同樣的問題。 解決辦法是通過addView()將RadioButton添加到RadioGroup后改變其狀態。 我想這也是 BAKUS 試圖通過他的示例代碼所說的。

這里復制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM