Android学习分享-常见控件05-RadioButton和CheckBox详解

本节引言

今天要和大家分享的是Android控件是RadioButton(单选按钮)和CheckBox(复选框)。放在一起讲的原因主要是这两个控件用法比较相似,正好也可以找出不同与区别。

RadioButton的用法

RadioButton介绍

我把Android API里面的介绍简单翻译了一下,毕竟官方的解释言简意赅,更能够让大家理解。

RadioButton:单选按钮是一个双状态按钮,可以选中或取消选中。当单选按钮没有被选中时,用户可以按或单击它来选中它。 然而,与复选框相反,一旦选中,用户就不能取消选中的单选按钮。
单选按钮们通常在RadioGroup中一起使用。当几个单选按钮位于RadioGroup内时,选中一个单选按钮可取消选中所有其他单选按钮。

从API的说法来看,主要有两点:

  1. 用户可以通过按或点击的操作来选中RadioButton,与CheckBox相反,一旦选中就不能取消选中(准确的说是再次点击或按RadioButton无法取消选中)。
  2. RadioButton一般放在RadioGroup中使用。(这样才能体现“单选”的特性)

API的解释中提到了RadioGroup,它是什么呢?
RadioGroup的作用是盛放RadionButton,RadioButton只有在它的包裹之下,才会有“单选”的特性。
为了理解这句话,我们用代码来验证,话不多说,上代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.radiobuttonandcheckboxdemo.MainActivity">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"/>
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"/>

</LinearLayout>

效果图:
这里写图片描述

代码中把RadioButton放在了LinearLayout(线性布局)中使用,可以发现“男”和“女”两个RadioButton都可以选中,并不是单选的。现在我把LinearLayout改成RadioGroup,会发生什么呢?

<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.radiobuttonandcheckboxdemo.MainActivity">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"/>
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"/>

</RadioButton>

效果图:
这里写图片描述

上述代码仅仅是把LinearLayout改成了RadioGroup,我们就只能选中“男”或“女”了,RadioButton就具有单选性了。

RadioButton实用用法

在上面介绍RadioButton时,其实已经简单地使用它了,接下来介绍一下关于RadioButton的常用方法。

1.RadioButton的事件处理
我们经常要获取选中RadioButton的事件,并对其进行相关的业务处理。现在介绍一下获取RadioButton事件的方法,先看以下的效果图:
这里写图片描述
我们点击不同的RadioButton,就弹出Toast显示提示信息。代码如下:
XML布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值