美文网首页
2019-09-17 手势监听扩展

2019-09-17 手势监听扩展

作者: 兣甅 | 来源:发表于2019-09-17 20:32 被阅读0次
fun View.addGesture(call: (gesture: GestureEnum) -> Unit) {
  var mPosX = 0f
  var mPosY = 0f
  var mCurPosX = 0f
  var mCurPosY = 0f
  setOnTouchListener { v, event ->
    when (event.action and MotionEvent.ACTION_MASK) {
      MotionEvent.ACTION_DOWN -> {
        mPosX = event.x
        mPosY = event.y
      }
      MotionEvent.ACTION_MOVE -> {
        mCurPosX = event.x
        mCurPosY = event.y
      }
      MotionEvent.ACTION_UP -> {
        if (mCurPosY - mPosY > 0
            && (abs(mCurPosY - mPosY) > 25)
            && (abs(mCurPosY - mPosY) > abs(mCurPosX - mPosX))
        ) {
          //上向下滑動
          call.invoke(GestureEnum.BOTTOM)
        } else if (mCurPosY - mPosY < 0
            && (abs(mCurPosY - mPosY) > 25)
            && (abs(mCurPosY - mPosY) > abs(mCurPosX - mPosX))
        ) {
          //下向上滑动
          call.invoke(GestureEnum.TOP)
        } else if (mCurPosX - mPosX > 0
            && (abs(mCurPosX - mPosX) > 25)
            && (abs(mCurPosX - mPosX) > abs(mCurPosY - mPosY))
        ) {
          //左向右滑動
          call.invoke(GestureEnum.RIGHT)
        } else if (mCurPosX - mPosX < 0
            && (abs(mCurPosX - mPosX) > 25)
            && (abs(mCurPosX - mPosX) > abs(mCurPosY - mPosY))
        ) {
          //右向左滑动
          call.invoke(GestureEnum.LEFT)
        }
      }
    }
    true
  }
}
enum class GestureEnum {
  TOP,
  BOTTOM,
  LEFT,
  RIGHT
}

相关文章

网友评论

      本文标题:2019-09-17 手势监听扩展

      本文链接:https://www.haomeiwen.com/subject/abicuctx.html