Android: RadioGroup — как настроить прослушиватель событий

Насколько я понимаю, чтобы определить, установлен ли флажок, и выяснить, отмечен он или нет, можно использовать следующий код:

cb=(CheckBox)findViewById(R.id.chkBox1);
        cb.setOnCheckedChangeListener(this);

public void onCheckedChanged(CompoundButton buttonView, 
    boolean isChecked) { 
        if (isChecked) { 
            cb.setText("This checkbox is: checked"); 
        } 
        else { 
            cb.setText("This checkbox is: unchecked"); 
        } 
    }

Однако я не могу понять логику того, как сделать это для радиогруппы.

Вот xml для моей RadioGroup:

<RadioGroup android:id="@+id/radioGroup1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio1" android:checked="true" 
    android:text="RadioButton1">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio2" android:text="RadioButton2" android:checked="true">
    </RadioButton>
    <RadioButton android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/radio3" android:text="RadioButton3">
    </RadioButton>
</RadioGroup>

Вопрос: Нужно ли мне настраивать другой слушатель, или уже существующий слушатель также "зарегистрирует" эту группу?

Кроме того, должен ли слушатель быть настроен на RadioGroup или RadioButton?


person Ryan    schedule 21.07.2011    source источник


Ответы (4)


Вот как вы получаете проверенную радиокнопку:

// This will get the radiogroup
RadioGroup rGroup = (RadioGroup)findViewById(r.id.radioGroup1);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());

Чтобы использовать прослушиватель, вы делаете это:

// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        // This will get the radiobutton that has changed in its check state
        RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
        // This puts the value (true/false) into the variable
        boolean isChecked = checkedRadioButton.isChecked();
        // If the radiobutton that has changed in check state is now checked...
        if (isChecked)
        {
            // Changes the textview's text to "Checked: example radiobutton text"
            tv.setText("Checked:" + checkedRadioButton.getText());
        }
    }
});
person A. Abiri    schedule 21.07.2011
comment
он говорит: локальная переменная rgroup, возможно, не была инициализирована - person Ryan; 21.07.2011
comment
Я просто написал эту первую строку, чтобы рассказать вам, что такое rGroup. Чтобы получить rGroup, нужно написать так: RadioGroup rGroup = (RadioGroup)findViewById(R.id.radioGroup1); - person A. Abiri; 21.07.2011
comment
Я не понимаю, он говорит мне, что радиогруппа проверена... но не говорит мне, какая радиокнопка проверена. Я что-то пропустил? - person Ryan; 21.07.2011
comment
Взгляните на мой ответ еще раз. Я отредактировал его и поставил комментарии к каждой строке, чтобы вы знали, что я делаю. Кроме того, проверенный идентификатор — это не имя радиокнопки, а уникальный идентификатор радиокнопки. - person A. Abiri; 21.07.2011
comment
Это сработало отлично, а также научило меня, как все это подключено сзади, большое спасибо! - person Ryan; 21.07.2011
comment
Я никогда не понимал, как это работает раньше, но ваш пример кода и комментарии заставили лампочку наконец загореться. - person sXe; 21.01.2015

Это должно быть что-то вроде этого.

RadioGroup rb = (RadioGroup) findViewById(R.id.radioGroup1);
rb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {

            }
        }

    });

Основываясь на checkedId, вы бы знали, какая из радиокнопок была нажата, а затем использовали приведенный выше код, чтобы выяснить, отмечена она или нет. Это домашнее задание. ;)

person PravinCG    schedule 21.07.2011
comment
Ваш код работает, но я убрал переключатель и вместо этого добавил это: tv.setText(blah:+checkedId); но это дает мне какие-то странные числа для checkedID :( - person Ryan; 21.07.2011
comment
CheckedId — это идентификатор радиокнопки, на которую нажали в группе. Вам нужно использовать findViewbyId, чтобы понять это. - person PravinCG; 28.05.2014
comment
Я ожидал бы, что это сработает, но это не так. Когда я меняю выбранную радиокнопку на трехкнопочном элементе управления, я получаю 3 проверенных уведомления об изменении. Кажется, по одному на кнопку. Но для первого уведомления кнопка для checkedId имеет значение false для Checked. Решение Абири работает для меня. - person Frank Schwieterman; 15.11.2016

Использование Switch лучше:

radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup arg0, int id) {
        switch (id) {
        case -1:
          Log.v(TAG, "Choices cleared!");
          break;
        case R.id.chRBtn:
          Log.v(TAG, "Chose Chicken");
          break;
        case R.id.fishRBtn:
          Log.v(TAG, "Chose Fish");
          break;
        case R.id.stkRBtn:
          Log.v(TAG, "Chose Steak");
          break;
        default:
          Log.v(TAG, "Huh?");
          break;
        }
      }
    });
person Diego Venâncio    schedule 11.08.2017
comment
Выдает следующее предупреждение: Идентификаторы ресурсов не будут окончательными в Android Gradle Plugin версии 5.0, избегайте их использования в операторах switch case. - person Luís Henriques; 28.06.2021

Если вы хотите увидеть, какая радиокнопка отмечена или выбрана в группе радио, используйте следующее:

//1. declare the radio group and the radio Button in the java file.
RadioGroup radiobtn;
RadioButton radio;
Button btnClick;
 //the radio is the element of the radiogroup which will assigned when we select the radio button
 //Button to trigger the toast to show which radio button is selected of the radio group


//2. now define them in the java file
radiobtn = findViewById(R.id.radiobtn);
btnClick = findViewById(R.id.btnClick);
 //we are instructing it to find the elements in the XML file using the id


//3. Now Create an on Click listener for the button
btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int selectedId = radiobtn.getCheckedRadioButtonId();
             //we are defining the selectId and then we are fetching the id of the checked radio button using the function getCheckedRadioButton()
            radio = findViewById(selectedId);
             //now the radioButton object we have defined will come into play, we will assign the radio to the radio button of the fetched id of the radio group
            Toast.makeText(MainActivity.this,radio.getText(),Toast.LENGTH_SHORT).show();
             //we are using toast to display the selected id of the radio button
             //radio.getText() will fetch the id of the radio Button of the radio group
        }
    });
person Alex Ed    schedule 23.09.2019