Good day. I am a novice. I am writing my first test program. I can not figure out how to write a condition to check whether the correct radio button is selected or not. Help me please.

@Override public void onClick(View v) { RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.radio_group); int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId())); int id = v.getId();// id кнопки if (id == R.id.resalt) { if (index == -1) { Toast toast = Toast.makeText(this, "Пожалуйста, выберите один из вариантов", Toast.LENGTH_SHORT); toast.show(); }// проверка нажал ли юзер вообще на radiobutton if (index == 0) { как написать сравнение с переменной правильного ответа } }// вибран 1 radiobutton 
  • one
    The books of Brown Hardy "Android. Programming for professionals" and Paul Detela "Android for developers" understand in detail the examples of developing a quiz application (test), I'm sure these books will help you a lot. - pavlofff
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

I will explain with an example.

Suppose there is a layuot :

 <RadioGroup android:id="@+id/radio_button_group" android:layout_width="match_parent" android:layout_height="wrap_content"> <RadioButton android:id="@+id/first_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First"/> <RadioButton android:id="@+id/second_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Second"/> <RadioButton android:id="@+id/third_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Third"/> </RadioGroup> 

Further:

 private RadioGroup mRadioButtonGroup; ... mRadioButtonGroup = (RadioGroup) findViewById(R.id.radio_button_group); ... int radioButtonID = mRadioButtonGroup.getCheckedRadioButtonId(); View radioButton = mRadioButtonGroup.findViewById(radioButtonID); if (radioButton == null) { Toast.makeText(getApplicationContext(), "Пункт не выбран!", Toast.LENGTH_SHORT).show(); return; } switch (radioButton.getId()) { case R.id.first_radio_button: Toast.makeText(getApplicationContext(), "Выбран первый пункт", Toast.LENGTH_SHORT).show(); break; case R.id.second_radio_button: Toast.makeText(getApplicationContext(), "Выбран второй пункт", Toast.LENGTH_SHORT).show(); break; case R.id.third_radio_button: Toast.makeText(getApplicationContext(), "Выбран третий пункт", Toast.LENGTH_SHORT).show(); break; } 

In your example, as far as I understand, the number of the selected item is index , respectively, you can process this value with the help of switch – case .