安卓控件之单选按钮 (RadioButton和RadioGroup)

概述:

RadioButton是单选按钮,可提供若干选项方便用户进行选择操作,且在一组选项中只能选择一个。

RadioGroup继承自ViewGroupRadioButton结合使用,将若干RadioButton选项组合为一组。

属性和方法:

RadioButton的常用属性及方法

XML属性

方法

备注

android:text

setText(CharSequence)

设置单选按钮文字

android:button

setButtonDrawable(int)

设置单选按钮图形,常用于取消单选按钮默认图形,如:androidbutton=”@null”

android:checked

 

设置单选按钮的选择状态true表示选择,false表示未选择,但单选按钮的选择状态并不能通过该属性实现,而是通过RadioGroupcheck(int)方法实现

 RadioGroup的常用属性及方法

XML属性

方法

备注

android:orientation

 

设置单选按钮的排列方式”horizontal”:水平排列,”vertical”:垂直排列

 

check(int id)

设置单选按钮组的默认选项

实例

总结:

RadioButton必须和RadioGroup连用

checked属性:true表示选中,默认的是false




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Android Studio中,RadioButtonRadioGroup是常用的单选控件RadioButton用于单个选项,而RadioGroup用于将多个RadioButton组合在一起,以便用户可以从中选择一个选项。 以下是一个使用RadioGroupRadioButton的示例: 1. 在XML布局文件中添加RadioGroupRadioButton: ```xml <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> ``` 2. 在Java代码中获取RadioGroupRadioButton,并设置选中的选项: ```java RadioGroup radioGroup = findViewById(R.id.radioGroup); RadioButton radioButton1 = findViewById(R.id.radioButton1); RadioButton radioButton2 = findViewById(R.id.radioButton2); RadioButton radioButton3 = findViewById(R.id.radioButton3); // 设置默认选中的选项 radioButton1.setChecked(true); // 监听选项变化 radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.radioButton1: // 选中了Option 1 break; case R.id.radioButton2: // 选中了Option 2 break; case R.id.radioButton3: // 选中了Option 3 break; } } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值