Android RadioButton Guide
In Android, a RadioButton is a type of radio button widget that is typically used in conjunction with a RadioGroup to select one option from several choices. The RadioButton can be declared in the XML layout file and its text, style, and listeners can be dynamically set in Java code.
To use a RadioButton, you first need to declare the RadioButton and RadioGroup in the XML layout file, for example:
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
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" />
</RadioGroup>
Next, in the Java code, you can use the findViewById() method to get the RadioButton and RadioGroup objects, and set listeners for the RadioButton to track the option selected by the user.
RadioGroup radioGroup = findViewById(R.id.radioGroup);
RadioButton radioButton1 = findViewById(R.id.radioButton1);
RadioButton radioButton2 = findViewById(R.id.radioButton2);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton radioButton = findViewById(checkedId);
if (radioButton != null) {
// 当选项变化时执行的操作
String selectedOption = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), "Selected option: " + selectedOption, Toast.LENGTH_SHORT).show();
}
}
});
By using the code above, we can display a Toast message when a RadioButton is selected to inform the user of their choice. This way, we can achieve the basic functionality of a RadioButton.