Радиокнопка - это графический элемент управления, который позволяет пользователю выбрать только один из предопределенного набора взаимоисключающих параметров. Когда вы пытаетесь использовать его в Android, это может немного сбивать с толку, если не понимать. Приведенные ниже коды дадут вам лучшее понимание того, как использовать переключатели в Android при условии, что мы разрабатываем приложение для викторин.

Случай 1. Использование события прослушивания

/*XML when using listening event*/
<RadioGroup
    android:id="@+id/android_question_one"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<RadioButton
        android:id="@+id/android_virtual_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/question_margin"
        android:layout_marginLeft="@dimen/question_margin"
        android:layout_marginRight="@dimen/question_margin"
        android:layout_marginStart="@dimen/question_margin"
        android:layout_marginTop="@dimen/question_margin"
        android:background="@drawable/semi_rounded_corners"
        android:padding="@dimen/text_padding"
        android:text="@string/android11"
        android:textColor="@color/colorGrey" />
//other radio buttons goes here
</RadioGroup>

Код Java для случая 1

Обратите внимание, что слушатели должны быть установлены в переменной, содержащей идентификатор радиогруппы.

public class AndroidActivity extends AppCompatActivity {
    int score = 0;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android);
//find the id of the RadioGroup and store it in a variable
        RadioGroup question1RadioGroup = (RadioGroup) findViewById(R.id.android_question_one);
        question1RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//set a listener on the RadioGroup
            @Override
            public void onCheckedChanged(RadioGroup view, @IdRes int checkedId) {
                //checkedId refers to the selected RadioButton
                //Perform an action based on the option chosen
                if (checkedId == R.id.android_virtual_device) {
                    getScore(1);
                } else {
                    getScore(0);
                }
            }
        });
}
// calculate the score
    private void getScore(int current_score) {
        score += current_score;
    }

Случай 2. Использование события onClick

/*XML when using onClick event*/
<RadioGroup
    android:id="@+id/android_question_one"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
<RadioButton
        android:id="@+id/android_virtual_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/question_margin"
        android:layout_marginLeft="@dimen/question_margin"
        android:layout_marginRight="@dimen/question_margin"
        android:layout_marginStart="@dimen/question_margin"
        android:layout_marginTop="@dimen/question_margin"
        android:background="@drawable/semi_rounded_corners"
        android:onClick="question1"
        android:padding="@dimen/text_padding"
        android:text="@string/android11"
        android:textColor="@color/colorGrey" />
//other radio buttons goes here
</RadioGroup>

Код Java для случая 2

public class AndroidActivity extends AppCompatActivity {
    int score = 0;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android);
}
/*Calculate the score for each question*/
    public void question1(View view) {
//find the id of the RadioGroup and store it in a variable
        RadioGroup question1RadioGroup = (RadioGroup) findViewById(R.id.android_question_one);
//Get the id of the RadioButton that is checked and store it as an integer variable.
        int answerId1 = question1RadioGroup.getCheckedRadioButtonId();
//Perform an action based on the option chosen
        if (answerId1 == R.id.android_virtual_device) {
            getScore(1);
        } else {
            getScore(0);
        }
    }
// calculate the score
    private void getScore(int current_score) {
        score += current_score;
    }

Использование варианта 1 предпочтительнее, чем вариант 2, хотя оба могут использоваться для достижения одного и того же результата.

Продолжайте кодировать!

Спасибо за чтение!

Если вам понравилась моя статья, нажмите этот значок 👏 ниже как можно больше раз, добавьте закладку, поделитесь ею со своими друзьями и следуйте за мной, чтобы увидеть больше историй. Не стесняйтесь задавать вопросы. Жду отзывов.