Android单选按钮RadioButton怎么使用

1485
2023/7/9 21:04:30
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

使用RadioButton的步骤如下:

  1. 在XML布局文件中添加RadioButton控件:
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项2" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项3" />
  1. 在Java代码中获取RadioButton控件对象,并为其设置点击事件:
RadioButton radioButton1 = findViewById(R.id.radioButton1);
RadioButton radioButton2 = findViewById(R.id.radioButton2);
RadioButton radioButton3 = findViewById(R.id.radioButton3);
radioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击选项1时执行的操作
}
});
radioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击选项2时执行的操作
}
});
radioButton3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击选项3时执行的操作
}
});
  1. 如果需要实现只能选择一个选项的效果,可以使用RadioGroup包裹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="选项1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项2" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项3" />
</RadioGroup>
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = findViewById(checkedId);
// 获取被选中的RadioButton的操作
}
});

以上就是使用RadioButton的基本步骤。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: android开启线程的方法的是什么