Как получить выбранный индекс RadioGroup в Android
Есть ли простой способ получить выбранный индекс RadioGroup в 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.
Ответы
Ответ 1
Вы должны быть в состоянии сделать что-то вроде этого:
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();
Ответ 2
Это должно работать,
int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
Ответ 3
У вас может быть ссылка на радиогруппу и использовать 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
}
}
Ответ 4
попробуйте это
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);
}
});
Ответ 5
Вы можете использовать OnCheckedChangeListener или можете использовать getCheckedRadioButtonId()
Ответ 6
Вы можете использовать:
RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
Ответ 7
//использовать для получения идентификатора выбранного элемента
int selectedID = myRadioGroup.getCheckedRadioButtonId();
//получить представление выбранного элемента
View selectedView = (View)findViewById( selectedID);
Ответ 8
Он отлично работал у меня таким образом:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
int radioButtonID = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
String selectedtext = (String) radioButton.getText();
Ответ 9
Все, что вам нужно, это сначала установить значения для вашего 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
Ура!
Ответ 10
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();
}
});
Ответ 11
int index_selected = radio_grp.indexOfChild(radio_grp
.findViewById(radio_grp.getCheckedRadioButtonId()));
Ответ 12
вы можете сделать
findViewById
из группы радиостанций.
Вот пример:
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
Ответ 13
просто используйте это:
int index = 2;
boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();
Ответ 14
Вы можете просто
-declare радиогруппа и радиокнопка из метода onCreate
private RadioGroup GrupName;
private RadioButton NameButton;
-set идентификатор представления в методе onCreate
GrupName = (RadioGroup) findViewById(R.id.radioGroupid);
-take идентификатор радиокнопки, выбранный с помощью
int id = GroupName.getCheckedRadioButtonId();
-use идентификатор, соответствующий выбранному представлению кнопки
NameButton = (RadioButton) findViewById(id);
-finally получить значение переключателя
String valueExpected = NameButton.getText().toString();
--- PS: ЕСЛИ ВЫ ХОТИТЕ ЦЕННОСТЬ INT, ТОГДА ВЫ МОЖЕТЕ ЕГО ЛИШИТЬСЯ
int valueExpectedIn = Integer.parseInt(valueExpected);
Ответ 15
Kotlin:
val selectedIndex = radioButtonGroup?.indexOfChild(
radioButtonGroup?.findViewById(
radioButtonGroup.getCheckedRadioButtonId())
)