软件编程
位置:首页>> 软件编程>> Android编程>> Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

作者:Shewyoo  发布时间:2023-02-06 18:20:42 

标签:Android,CheckBox,Switch,RadioButton

前言 

Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

CompoundButton在XML文件中主要使用下面两个属性。

  • checked:指定按钮的勾选状态,true表示勾选,false则表示未勾选,默认为未勾选。

  • button:指定左侧勾选图标的图形资源,如果不指定就使用系统的默认图标。

CompoundButton在java代码中主要使用下列4种方法。

  • setChecked:设置按钮的勾选状态。

  • setButtonDrawable:设置左侧勾选图标的图形资源。

  • setOnCheckedChangeListener:设置勾选状态变化的 * 。

  • isChecked:判断按钮是否勾选。

一、复选框CheckBox

<CheckBox
       android:id="@+id/ck_system"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:padding="5dp"
       android:text="系统CheckBox"/>

Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

二、开关按钮Switch

Switch是开关按钮,它在选中与取消选中时可展现的界面元素比复选框丰富。

Switch控件新添加的XML属性说明如下:

  • textOn:设置右侧开启时的文本。

  • textOff:设置左侧关闭时的文本。

  • track:设置开关轨道的背景。

  • thumb:设置开关标识的图标。

<Switch
           android:id="@+id/sw_status"
           android:layout_width="80dp"
           android:layout_height="30dp"
           android:padding="5dp"/>

Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

三、单选按钮RadioButton

单选按钮要在一组按钮种选择其中一项,并且不能多选,这要求有个容器确定这组按钮的范围,这个容器便是单选组RadioGroup。

RadioGroup实际上是个布局,同一组RadioButton都要放在同一个RadioGroup节点下,除了RadioButton,也允许放置其他控件。

单选组的用法

判断选中了哪个单选按钮,通常不是监听某个单选按钮,而是监听单选组的选中事件。

RadioGroup常用的3个方法:

  • check:选中指定资源编号的单选按钮。

  • getCheckedRadioButtonId:获取选中状态单选按钮的资源编号。

  • setOnCheckedChangeListener:设置单选按钮勾选变化的 * 。

<TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="请选择性别"/>
   <RadioGroup
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
       <RadioButton
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:text="男"/>
       <RadioButton
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:text="女"/>
   </RadioGroup>

Android复选框CheckBox与开关按钮Switch及单选按钮RadioButton使用示例详解

来源:https://blog.csdn.net/Tir_zhang/article/details/126973628

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com