Set selected index of an Android RadioGroup

前端 未结 7 1069
予麋鹿
予麋鹿 2021-02-01 11:52

Is there a way to set the selected index of a RadioGroup in android, other than looping through the child radiobuttons and selecting checking the radio button at the selected in

7条回答
  •  一个人的身影
    2021-02-01 12:07

    This Worked For me, I created radio button dynamically by

      private void createRadioButton() {
    
        RadioButton[] rb = new RadioButton[5];
    
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                1.0f);
    
        radioGroup.setOrientation(RadioGroup.HORIZONTAL);
    
        for (int ID = 0; ID < 5; ID++) {
            rb[ID] = new RadioButton(this);
            rb[ID].setLayoutParams(layoutParams);
            rb[ID].setText("Button_Text");
            radioGroup.addView(rb[ID]); //the RadioButtons are added to the radioGroup instead of the layout
        }
    }
    

    Now Check a button using,

    int radio_button_Id = radioGroup.getChildAt(index).getId();
    
    radioGroup.check( radio_button_Id );
    

提交回复
热议问题