Есть ли простой способ получить выбранный индекс 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.
Вы должны сделать что-то вроде этого:
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 ()
Вы можете использовать:
RadioButton rb = (RadioButton) findViewById(rg.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();
int index_selected = radio_grp.indexOfChild(radio_grp .findViewById(radio_grp.getCheckedRadioButtonId()));
Все, что вам нужно, это сначала установить значения для вашего 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(); } });
ты можешь сделать
findViewById
Из радиогруппы.
Вот пример:
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
Просто используйте это:
int index = 2; boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();