单项选择RadioButton和多项选择CheckBox的使用
前言:
在上一章我写了关于安卓UI控件之Button,这一章就来讲解下它的子类RadioButton和CheckBox。
在Android中,可以通过RadioButton和RadioGroup的组合来实现单项选择的效果。而多项选择则是通过CheckBox来实现的。
1、单选选择RadioButton
我们知道,一个单项选择是由两部分组成的,分别是前面的选择按钮和后面的“答案”。
选择按钮可以通过RadioButton来实现,而“答案”则可以通过RadioGroup来实现。
具体的实现步骤如下:
首先,在布局文件中定义一个TextView控件,用来显示问题。
然后,再在布局文件中定义一个RadioGroup控件,用来显示答案。
最后,再在RadioGroup控件中定义四个(根据需求而定)RadioButton控件,并将“答案”分别赋给每个选项。
如下是单项选择的XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--题目-->
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android内核是基于什么系统?"
android:textSize="24sp"
/>
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RadioButton
android:id="@+id/radiobutton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Windows"
/>
<RadioButton
android:id="@+id/radiobutton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mac os"
/>
<RadioButton
android:id="@+id/radiobutton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Linux"
/>
<RadioButton
android:id="@+id/radiobutton4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="嵌入式系统"
/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:layout_marginTop="50dp"
android:text="进入下一项测试"
/>
</LinearLayout>
因为是单项选择,所以各个选项之间存在互斥性,即仅能选中其中的某一个选项。
那么如何来确定用户的选择是否正确,并给出相应的提示信息呢?
要确定用户的选择是否正确,需要知道用户选择的是选项中的哪一项,
这可以通过为RadioGroup设置事件监听器setOnCheckedChangeListener来实现。
通过该事件监听器便可以判断出用户点击的是哪一个RadioButton了。然后,再使用Toast来显示相应的提示信息即可。
用上述方案实现单项选择demo的java源代码如下:
<