安卓开发教程23: RadioButton 单选按钮

328 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第23天,点击查看活动详情

前面我们对 CompoundButton 复合按钮以及继承自他的 CheckBox 、 Switch 控件,进行了学习,今天我们再来学习一个 继承自 CompoundButton 的控件 RadioButton 单选按钮 。

RadioButton 基本用法

话不多说让我们直接上手来写一个 RadioButton:

代码:

<RadioGroup
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RadioButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="140cm一下" />

    <RadioButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="140cm-180cm"/>

    <RadioButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="180cm以上"/>
</RadioGroup>

效果:

image.png

说明:

我们看到这里写了个身高的选项,当然了身高不可能有多个选项嘛,所以肯定是在一组选项中选择一个区间,那么同理 RadioButton 代表了每一个选项,它也在一个组 RadioGroup 里面。

我们看到 RadioGroup 也有个 orientation 属性,用来控制 RadioButton 水平排列或者垂直排列(水平排列需要设置 RadioButton 的 宽度为 0dp , weight 为 相应的比例 )。

image.png

RadioButton 选项按钮也可以换成 UI自定义的图案,用法如同 CheckButton 一样设置 button属性。

image.png

RadioButton 事件处理

我们用当选按钮肯定是要在某一组中选中一项,最终获取选中的是哪一项,所以我们得给这个组 RadioGroup 加监听事件,而不是某一项 RadioButton。

那么 RadioGroup 虽然与 CheckButton 控件一样用的都是 setOnCheckedChangeListener 监听器,但 RadioGroup 在监听器中传递的是 nnew RadioGroup.OnCheckedChangeListener,它的 onCheckedChanged 参数为 radioGroup (组自身) 与 i (选中的RadioButton 的 id) 。

@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
    if(i == R.id.rb_1){
        //执行某某
    }else if(i == R.id.rb_2){
        //执行某某
    }else if(i == R.id.rb_3){
        //执行某某
    }
}

我们经常还好遇到一种情况,用户刚打开页面,某一组会默认被选中一个,或者进行了某些 操作后,某一组会联动选中一个选项。这时候我们用 check 方法就可以了,它传入的是要被选择的 RadioButton 的 id。


RadioGroup rg_1 = findViewById(R.id.rg_1);
rg_1.check(R.id.rb_2);

还有些情况,比如我们点击下方确认按钮的时候想要获取 选中的 RadioButton,我们可以使用 getCheckedRadioButtonId 方法。获取到的是选中的 RadioButton 的 id,如果没有选择项则为 -1。

public void onClick(View view) {
    rg_1.getCheckedRadioButtonId()
}

这些就是 RadioButton 控件比较常用的属性和方法。其实学习过 CheckButton 和 Switch 之后再来学习 RadioButton是非常简单的,它们很多数的方法和属性都是通用的。还是那句话,这些控件和它们的属性方法都需要我们根据实际情况灵活的搭配使用。