2019-09-17 手势监听扩展
2019-09-17 本文已影响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
}