在Android中,RadioButton是一種單選按鈕控件,通常與RadioGroup一起使用,用于在幾個(gè)可選項(xiàng)中選擇一個(gè)選項(xiàng)。RadioButton可以在XML布局文件中聲明,并且可以在Java代碼中動(dòng)態(tài)設(shè)置其文本、樣式和監(jiān)聽器等屬性。
使用RadioButton時(shí),首先需要在XML布局文件中聲明RadioButton和RadioGroup,例如:
<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>
然后在Java代碼中,可以通過(guò)findViewById()方法獲取RadioButton和RadioGroup對(duì)象,并為RadioButton設(shè)置監(jiān)聽器,監(jiān)聽用戶選擇的選項(xiàng):
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) {
// 當(dāng)選項(xiàng)變化時(shí)執(zhí)行的操作
String selectedOption = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), "Selected option: " + selectedOption, Toast.LENGTH_SHORT).show();
}
}
});
通過(guò)上面的代碼,可以實(shí)現(xiàn)在RadioButton被選中時(shí)彈出Toast提示用戶選擇了哪個(gè)選項(xiàng)。這樣就可以實(shí)現(xiàn)RadioButton的基本用法。