Android RadioGroup: Basic Usage Guide

A RadioGroup is a basic control in Android used to manage a group of RadioButtons, where only one can be selected. Here is the basic usage of RadioGroup:

  1. Add a RadioGroup and multiple RadioButtons in the layout file.
<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 1" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 2" />

    <RadioButton
        android:id="@+id/radioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 3" />
</RadioGroup>
  1. In the Activity, obtain the RadioGroup object and set the selection listener.
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 获取选中的RadioButton的id
        RadioButton radioButton = findViewById(checkedId);
        // 获取选中的RadioButton的文本
        String text = radioButton.getText().toString();
        // 在这里处理选中的RadioButton
    }
});

In the listener, you can obtain the id of the selected RadioButton by using checkedId and then retrieve the RadioButton object using the findViewById method. Finally, you can handle the selected RadioButton as needed.

The above is the basic usage of RadioGroup, which allows for easy management of a group of RadioButtons and enables single selection functionality.

bannerAds