目录

onTouch全局监听滑动事件

问题现象

如何全局监听滑动事件,控制紫色子组件的显示隐藏,实现下图的功能?

背景知识

onTouch:手指触摸动作触发该回调。鼠标左键按下时对应的事件也会转化成触摸事件并触发该回调。

解决方案

  1. 创建一个紫色的stack组件,设置visibility属性,通过判断标记isDirectShowPlayPanel来控制组件的显示与隐藏。
    if (this.isShowPlayPanel) {
      Stack() {
    
    
      }
      .width('100%')
      .height(80)
      .hitTestBehavior(HitTestMode.None)
      .backgroundColor('#785694')
      .margin({
        bottom: 50
      })
      .visibility(this.isDirectShowPlayPanel ? Visibility.Visible : Visibility.None)
      .position({ y: 600 })
      .transition(
        TransitionEffect
          .move(TransitionEdge.BOTTOM)
          .animation({
            duration: 500,
            curve: Curve.Friction
          })
      );
    }
  2. 使用onTouch监听全局的滑动,获取event对象,在TouchType.Up回调里获取滑动的距离和滑动的时间,计算出滑动的速度,速度大于零表示下滑,此时紫色组件显示;速度小于零表示上滑,此时紫色组件隐藏。

    注意:通过上下滑动来控制紫色组件的显示与隐藏。

    .onTouch((event: TouchEvent) => {
      if (!event) {
        return;
      }
      switch (event.type) {
        case TouchType.Down:
          this.startX = event.touches[0].displayX;
          this.startY = event.touches[0].displayY;
          this.startTime = event.timestamp;
          break;
        case TouchType.Move:
          break;
        case TouchType.Up:
          let endY = event.touches[0].displayY;
          let endTime = event.timestamp;
          let deltaTime = (endTime - this.startTime) / 1000000000;
          let speed = (endY - this.startY) / (deltaTime === 0 ? 1 : deltaTime);
          if (Math.abs(speed) > 800) {
            if (speed < 0) {
              this.isShowPlayPanel = false;
              this.isDirectShowPlayPanel = false;
            } else if (speed > 0) {
              this.isDirectShowPlayPanel = true;
              this.isShowPlayPanel = true;
            }
          }
          break;
      }
    });

全量代码示例如下:

效果图: