1.布局
xml
<View
android:id="@+id/v_moveUp"
android:layout_width="@dimen/dp_0"
android:layout_height="@dimen/dp_0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_TopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" >
</View>
2.监听事件
kotlin
private lateinit var gestureHandler: BaseGestureHandler //左右滑动切歌
------------------------------------------------------------------------------------
gestureHandler = object : BaseGestureHandler() {
override fun onSwipeRight() {
playNext()
}
override fun onSwipeLeft() {
playPrevious()
}
}
vMoveUp.isSoundEffectsEnabled = false
vMoveUp.setOnTouchListener { v, event ->
event?.let {
if (it.pointerCount >= 2) {
return@setOnTouchListener false
}
gestureHandler.onTouchEvent(it) } ?: true
}
vMoveUp.setOnSingleClickListener {
}
3.核心实现
kotlin
abstract class BaseGestureHandler {
val gestureDetector: GestureDetector
init {
gestureDetector = GestureDetector(object : GestureDetector.SimpleOnGestureListener() {
private val swipeThreshold = 100
private val swipeVelocityThreshold = 100
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
val pointCount = e1.pointerCount
val pointCount2 = e2.pointerCount
if (pointCount > 1 || pointCount2 > 1) {
return false
}
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > swipeThreshold && Math.abs(velocityX) > swipeVelocityThreshold) {
if (diffX > 0) {
onSwipeRight()
} else {
onSwipeLeft()
}
return true
}
}
return false
}
})
}
fun onTouchEvent(event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}
abstract fun onSwipeRight()
abstract fun onSwipeLeft()
}