HarmonyOS Toggle如何禁用自身的点击切换事件?

如题:HarmonyOS Toggle如何禁用自身的点击切换事件?

阅读 578
1 个回答

问题场景

使用Toggle控件时,我不需要它响应点击事件,开或关由另一个控件控制的

参考代码:

@Entry
@Component
struct Page240522215803016 {
  @State message: string = 'Hello World';
  @State isToggleOn: boolean = false
  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogExample({
      confirm: () => {
        this.onAccept()
      },
    }),
  })

  onAccept() {
    if (this.isToggleOn) {
      this.isToggleOn = false
    } else {
      this.isToggleOn = true
    }
  }

  build() {
    RelativeContainer() {
      Toggle({
        type: ToggleType.Switch,
        isOn: this.isToggleOn
      })// 调用onTouchIntercept修改该组件的HitTestMode属性
        .onTouchIntercept((event: TouchEvent) => {
          console.log("OnTouchIntercept + " + JSON.stringify(event));
          this.dialogController.open()
          return HitTestMode.None
        }).onChange((isOn: boolean) => {
        console.info("isOn:" + isOn)
        if (isOn) {
          // 需要执行的操作
        }
      })
    }.height('100%').width('100%')
  }
}

@CustomDialog
export struct CustomDialogExample {
  controller: CustomDialogController = new CustomDialogController({ builder: CustomDialogExample({}), })
  confirm?: () => void

  build() {
    Column() {
      Text('点击确认').fontSize(20).margin({ top: 10, bottom: 10 }).onClick(() => {
        this.controller.close()
        if (this.confirm) {
          this.confirm()
        }
      })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进