• 【Android】-- 按钮(复选框CheckBox、开关按钮Switch、单选按钮RadioButton)



     

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

    • checked:指定按钮的勾选状态,true表示勾选,false则表示未勾选,默认为未勾选。
    • button:指定左侧勾选图标的图形资源,如果不指定就使用系统的默认图标。

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

    • setChecked:设置按钮的勾选状态。
    • setButtonDrawable:设置左侧勾选图标的图形资源。
    • setOnCheckedChangeListener:设置勾选状态变化的监听器。
    • isChecked:判断按钮是否勾选。

    一、复选框CheckBox

    1. <CheckBox
    2. android:id="@+id/ck_system"
    3. android:layout_width="match_parent"
    4. android:layout_height="wrap_content"
    5. android:padding="5dp"
    6. android:text="系统CheckBox"/>

     二、开关按钮Switch

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

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

    • textOn:设置右侧开启时的文本。
    • textOff:设置左侧关闭时的文本。
    • track:设置开关轨道的背景。
    • thumb:设置开关标识的图标。
    1. <Switch
    2. android:id="@+id/sw_status"
    3. android:layout_width="80dp"
    4. android:layout_height="30dp"
    5. android:padding="5dp"/>

     三、单选按钮RadioButton

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

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

    单选组的用法

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

    RadioGroup常用的3个方法:

    • check:选中指定资源编号的单选按钮。
    • getCheckedRadioButtonId:获取选中状态单选按钮的资源编号。
    • setOnCheckedChangeListener:设置单选按钮勾选变化的监听器。
    1. <TextView
    2. android:layout_width="match_parent"
    3. android:layout_height="wrap_content"
    4. android:text="请选择性别"/>
    5. <RadioGroup
    6. android:layout_width="match_parent"
    7. android:layout_height="wrap_content">
    8. <RadioButton
    9. android:layout_width="match_parent"
    10. android:layout_height="wrap_content"
    11. android:layout_weight="1"
    12. android:text="男"/>
    13. <RadioButton
    14. android:layout_width="match_parent"
    15. android:layout_height="wrap_content"
    16. android:layout_weight="1"
    17. android:text="女"/>
    18. </RadioGroup>

     


  • 相关阅读:
    #循循渐进学51单片机#实例练习与经验累积#not.9
    2023-10-10 mysql-{mysql_alter_table}-出错后回滚-记录
    Golang goroutine 进程、线程、并发、并行
    Android源码笔记--恢复出厂设置
    Bootstrap(一)
    Android 动画和过渡
    mediapipe流水线分析 二
    华清远见嵌入式学习——驱动开发——作业1
    408 | 【计网】第二章 物理层 回顾
    《公共管理学》重点总结-陈振明版
  • 原文地址:https://blog.csdn.net/Tir_zhang/article/details/126973628