2024年11月5日 LiuJinTao
开关灯小案例
源代码示例
/**
* Toggle 切换按钮组件(两种状态)
*/
import { promptAction } from '@kit.ArkUI'
@Entry
@Component
struct WindowPage {
@State isOnState: boolean = false
build() {
Column({ space: 20 }) {
Text('HarmonyOS NEXT').fontWeight(FontWeight.Bold)
// TODO 模拟开关灯案例
Column({ space: 20 }) {
Text()
.height(100)
.width(2)
.backgroundColor(this.isOnState ? Color.White : Color.Black)
Image($r(this.isOnState ? 'app.media.open' : 'app.media.close')).width(40).height(40)
.position({x: 119, y: 99})
}
.width('80%')
.height(260)
.backgroundColor(Color.Black)
.borderRadius(15)
// 切换按钮组件的使用
Toggle({ type: ToggleType.Switch, isOn: this.isOnState})
.selectedColor("#FFBFA9")
.switchPointColor("#AAB396")
.selectedColor("#FF0")
// 通过 onChange事件处理该功能
.onChange((isOn: boolean) => {
this.isOnState = ! this.isOnState
if (this.isOnState) {
promptAction.showToast({ message: `开灯`})
} else {
promptAction.showToast({ message: `关灯`})
}
})
}
.height('100%')
.width('100%')
.padding(20)
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}