是否有一个简单的方法来获得在Android中一个RadioGroup的选定索引,或者我必须使用OnCheckedChangeListener来监听变化,并有一些东西,保持选定的最后一个索引?

示例xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

如果用户选择选项3,我想获取索引2。


当前回答

//获取所选项目的id

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//获取所选项目的视图

View selectedView = (View)findViewById( selectedID);

其他回答

这对我来说非常有效:

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();

你可以使用:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
        }
    });

你应该可以这样做:

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

如果RadioGroup包含其他视图(如TextView),则indexOfChild()方法将返回错误的索引。

要在RadioGroup上获得选定的RadioButton文本:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

您可以有一个对单选组的引用,并使用getCheckedRadioButtonId()来获得选中的单选按钮id。看这里

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

然后当你需要得到选定的无线电选项。

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}