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,"开关关闭了");
//实际开发:关闭某个设置
}
}
}
运行效果: