Как получить выбранный индекс Радиогруппы в Android
есть ли простой способ получить выбранный индекс Радиогруппы в Android или мне нужно использовать 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>
если пользователь выбирает option 3
Я хочу получить индекс, 2.
13 ответов
вы должны быть в состоянии сделать что-то вроде этого:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
если RadioGroup
содержит другие виды (например,TextView
), то indexOfChild()
метод вернет неправильный индекс.
чтобы получить выбранный текст RadioButton на RadioGroup
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();
Это должно работать,
int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
вы можете иметь ссылку на радиогруппу и использовать getCheckedRadioButtonId ()
чтобы получить проверенный идентификатор переключателя. Взгляните здесь
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
}
}
попробуй такое
RadioGroup group= (RadioGroup) getView().findViewById(R.id.radioGroup);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
View radioButton = radioGroup.findViewById(i);
int index = radioGroup.indexOfChild(radioButton);
}
});
вы можете использовать OnCheckedChangeListener или использовать getCheckedRadioButtonId ()
//использовать, чтобы получить идентификатор выбранного элемента
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, например:
RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);
radioButton.setId(1); //some int value
и тогда, когда этот космический радиобуттон будет выбран, вы можете вытащить его значение по идентификатору, который вы дали ему с
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
//should be inside the "radioGroup"
//in the XML
Ура!
radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);
btnDisplay=(Button)findViewById(R.id.button);
btnDisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedId=radioSexGroup.getCheckedRadioButtonId();
radioSexButton=(RadioButton)findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
}
});
int index_selected = radio_grp.indexOfChild(radio_grp
.findViewById(radio_grp.getCheckedRadioButtonId()));
можно сделать
findViewById
из радио-группы .
вот пример :
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
просто использовать это:
int index = 2;
boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();