本节引言
今天要和大家分享的是Android控件是RadioButton(单选按钮)和CheckBox(复选框)。放在一起讲的原因主要是这两个控件用法比较相似,正好也可以找出不同与区别。
RadioButton的用法
RadioButton介绍
我把Android API里面的介绍简单翻译了一下,毕竟官方的解释言简意赅,更能够让大家理解。
RadioButton:单选按钮是一个双状态按钮,可以选中或取消选中。当单选按钮没有被选中时,用户可以按或单击它来选中它。 然而,与复选框相反,一旦选中,用户就不能取消选中的单选按钮。
单选按钮们通常在RadioGroup中一起使用。当几个单选按钮位于RadioGroup内时,选中一个单选按钮可取消选中所有其他单选按钮。
从API的说法来看,主要有两点:
- 用户可以通过按或点击的操作来选中RadioButton,与CheckBox相反,一旦选中就不能取消选中(准确的说是再次点击或按RadioButton无法取消选中)。
- 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="