安卓开发教程24: Switch 开关按钮

1,343 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第24天,点击查看活动详情

上一篇文章中我们学习了 CheckBox 控件,今天我们接着来看行走江湖必备的控件 Switch 开关。

其实 Switch 控件 与 CheckBox 控件有很多一样的地方,比如属性和方法大部分一样,那是因为 他们都继承自 CompoundButton,让我们先来捋一下他们的继承关系。

CompoundButton 复合按钮

继承关系: View —> TextView —> Button —> CompoundButton —> CheckBox & Switch & RadidButton

OK 我们看到上一篇中学习的 CheckBox 和 今天学习的 Switch 以及下一篇中学习的 RadidButton 都继承自 CompoundButton类。

因为 CompoundButton 是抽象类,所以它不能直接使用,而是使用它的几个派生类如 CheckBox 、 Switch 、 RadidButton 。这些派生类均可使用 CompoundButton 的属性和方法。加之 CompoundButton 本身继承了Button 类,所以以上及几种按钮同时具备Button的属性和方法。

CompoundButton 常用属性

  1. checked 按钮勾选状态,true 代表选择,false 代表未选中
  2. button 按钮的图标资源,默认为系统默认

CompoundButton 常用方法

  1. setChecked 设置按钮的选中状态
  2. setButtonDrawable 设置按钮图标资源文件
  3. setOnCheckedChangeListener 设置按钮的监听器
  4. isChecked 判断按钮是否选择

言归正传接下来我们来看今天的学习内容 Switch 开关按钮。

Switch 基本用法

让我们先来写一个 Switch看一下效果:

代码:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

效果:

image.png

我们看到只是就单单只是一个开关而已,并不是我们日常看到的,前面有文字提示,后面是开关选项。

image.png

要实现这种效果就需要结合我们前面学习到的内容灵活使用了。

  1. 首先创建一个 LinearLayout 水平排列
  2. 然后创建一个 TextView 用于显示 左侧文本(宽度设置为 0dp 并加 权重 为1,令其自适应宽度)
  3. 最后创建一个 Switch 用于显示 右侧开关

代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="20dp">
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="这里是文本提示 "/>
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

如果我们想给开关加上文字提示. Switch 给我们提供了两个属性(注意:需要加上 showText=“true” 属性 才会起作用

  1. textOn, 设置右侧开启式的文本
  2. textOff,设置右侧关闭式的文本

代码:

<Switch
    android:id="@+id/sw_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:showText="true"
    android:textOn="开"
    android:textOff="关"/>

效果:

image.png

如果我们的应用需要根据UI定制按钮样式,Switch 给我们提供了两个属性,可以更方便的定制开关效果(需要指定相应的 drawable 文件)

  1. track,设置开关轨迹背景
  2. thumb,设置开关标识背景

代码:


<Switch
    android:id="@+id/sw_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:track="@drawable/switch_track"
    android:thumb="@drawable/switch_thumb"
   />

效果:

image.png

Switch 事件处理

Switch 的事件与 CheckBox 一样 使用 setOnCheckedChangeListener 监听器

代码:

@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    if(b){
        swt_1.setText("被选中");
    }else{
        swt_1.setText("这里是文本提示");
    }
}

到这里 Switch 开关按钮 常用的方法属性就介绍完毕了,这个控件在日常使用的频率很高,我们应该牢牢的掌握它,并且在日常使用中灵活搭配。