HarmonyOS开发39:Switch组件

Switch组件

实际开发中一般作为某些功能的开关。
一般开关的文字是不显示的。
一般只设置滑块和滑轨的颜色和样式。

滑道背景
ohos:track_element="#FF0000"
滑块颜色
ohos:thumb_element="#07C160"

在这里插入图片描述

示例:改变状态弹出吐司

本篇文章需要用到前面写的吐司弹框,记得提前加入到项目当中
同时,吐司弹框的代码可以做一个简化,如图:
在这里插入图片描述

ability_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Switch
        ohos:id="$+id:choose"
        ohos:height="40vp"
        ohos:width="100vp"
        ohos:text_state_on=""
        ohos:text_state_off=""
        ohos:text_size="20fp"
        />
<!--
    设置滑块
    ohos:thumb_element="#07C160"
    设置滑轨
    ohos:track_element="#FF0000"-->

</DirectionalLayout>

MainAbilitySlice.java代码:

package com.example.switchapplication.slice;

import com.example.switchapplication.ResourceTable;
import com.example.switchapplication.dialogUtils.ToastUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AbsButton;
import ohos.agp.components.Component;
import ohos.agp.components.Switch;

public class MainAbilitySlice extends AbilitySlice implements AbsButton.CheckedStateChangedListener {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //1.找到开关组件
        Switch choose = (Switch) findComponentById(ResourceTable.Id_choose);

        //2.给开关组件绑定事件
        //单击事件或状态改变事件
        choose.setCheckedStateChangedListener(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    //参数一:状态改变的组件
    //参数二:组件当前的状态
    @Override
    public void onCheckedChanged(AbsButton absButton, boolean b) {
        if(b){
            ToastUtils.showDialog(this,"开关开启了");
            //实际开发:打开某个设置
        }else{
            ToastUtils.showDialog(this,"开关关闭了");
            //实际开发:关闭某个设置
        }
    }
}

运行效果:
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GeniusAng丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值