Android 基础知识4-3.6 ToggleButton(开关按钮)&Switch(开关)详解

本文详细介绍了Android中的两种开关控件:ToggleButton和Switch,包括它们的简介、属性、使用示例和监听状态变化的方法。ToggleButtons允许自定义选中和未选中状态的文本和背景,而Switch提供了更多的属性定制,如滑动文字、滑块样式等。
摘要由CSDN通过智能技术生成

一、ToggleButton(开关按钮)

1.1、简介

        ToggleButton 类似开关有开和关两种状态,不同的状态下可以有不同的文本。

        public class ToggleButton extends CompoundButton
        Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF"。

        这是一种特殊的有两种状态的继承至CompoundButton的控件,在不同的状态会有高亮显示效果,既然是继承至CompoundButton,那我们也随便看一下CompoundButton的介绍:

 A button with two states, checked and unchecked. When the button is pressed
 or clicked, the state changes automatically.

1.2、属性

android:checked = “true”

默认为选中状态,反之false即是默认为非选中状态。

android:textOff = “张起灵” 未选中状态下的文本是张起灵

android:textOn = “张无忌” 选中状态下的文本是张无忌

1.3.1、示例1

效果图:

XML:

<ToggleButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="ToggleButton"
    android:textAllCaps="false"
    android:textOff="张起灵"
    android:textOn="张无忌" />

1.3.2、示例2

        同样的,我们可以监听不同的状态来设置不同的背景,来适配不同的使用场景,这个背景设置和Button中的一模一样。只是针对的状态不同而已,记得在Button中,我们的Drawable如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorAccent"></item>
    <item android:state_pressed="false" android:drawable="@color/colorPrimary"></item>
</selector>

在我们的ToggleButton中,我们的背景Drawable如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyxhzdm

你的鼓励是我创作的最大动力!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值