toggle组件设置拖动的同时如何屏蔽其本身的点击手势

toggle组件设置拖动的同时如何屏蔽其本身的点击手势

HarmonyOS
2024-07-22 12:21:11
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
janux

需要手动控制Toggle组件传入的默认值,例如在最上面自定义一个toggleIsOn的boolean变量然后,在onChange回调里面自己手动控制改变其的值。

import { hilog } from '@kit.PerformanceAnalysisKit'; 
 
@Entry 
@Component 
export struct TestDragToggle { 
  @State offsetX: number = 0; 
  @State offsetY: number = 0; 
  @State positionX: number = 0; 
  @State positionY: number = 0; 
  @State toggleIsOn: boolean = true; 
  private isDragging: boolean = false; 
 
  build() { 
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { 
      Toggle({ type: ToggleType.Button, isOn: this.toggleIsOn }) { 
        Text('Toggle') 
      } 
      .selectedColor(Color.Pink) 
      // onchange回调先于onActionEnd 
      .onChange((isOn: boolean) => { 
        hilog.info(0x0000, 'testTag', 'xxx %{public}s', `onClick Toggle, isOn: ${isOn}`); 
        console.info('isDragging======' + this.isDragging) 
        if (isOn == this.toggleIsOn) { 
          return 
        } else { 
          this.toggleIsOn = isOn 
        } 
        if (this.isDragging) { 
          this.toggleIsOn = !this.toggleIsOn 
        } 
      }) 
      .translate({ x: this.offsetX, y: this.offsetY }) 
      .gesture( 
        PanGesture() 
          .onActionStart((event: GestureEvent) => { 
            this.isDragging = true; 
          }) 
          .onActionUpdate((event: GestureEvent) => { 
            this.offsetX = this.positionX + event.offsetX; 
            this.offsetY = this.positionY + event.offsetY; 
          }) 
          .onActionEnd((event: GestureEvent) => { 
            this.positionX = this.offsetX; 
            this.positionY = this.offsetY; 
            this.isDragging = false; 
          }) 
      ) 
    } 
  } 
}
分享
微博
QQ
微信
回复
2024-07-22 20:05:36