gpt4 book ai didi

android - 通过使用 kotlin 向左或向右滑动来捕获事件

转载 作者:行者123 更新时间:2023-11-29 14:23:48 25 4
gpt4 key购买 nike

如何使用 kotlin 向左或向右滑动来捕获事件?

我已经实现了 OnTouchListener 来尝试捕捉一些东西,但是没有任何反应。

class MyClass : Fragment(), View.OnTouchListener {

lateinit var mRootView: View

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {


mRootView = inflater.inflate(myLayout, container, false)

mRootView.setOnTouchListener(this)

return mRootView
}

override fun onTouch(view: View?, event: MotionEvent?): Boolean {
println("test")
println(event?.actionMasked.toString())
return true
}
}

最佳答案

如果想这样做,尝试自定义触摸监听器实现 OnTouchListener

open class OnSwipeTouchListener : View.OnTouchListener {

private val gestureDetector = GestureDetector(GestureListener())

fun onTouch(event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}

private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {

private val SWIPE_THRESHOLD = 100
private val SWIPE_VELOCITY_THRESHOLD = 100

override fun onDown(e: MotionEvent): Boolean {
return true
}

override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
onTouch(e)
return true
}


override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
val result = false
try {
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight()
} else {
onSwipeLeft()
}
}
} else {
// onTouch(e);
}
} catch (exception: Exception) {
exception.printStackTrace()
}

return result
}
}

override fun onTouch(v: View, event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}

open fun onSwipeRight() {}

open fun onSwipeLeft() {}

open fun onSwipeTop() {}

open fun onSwipeBottom() {}
}

以及 View 的用法:

imageView.setOnTouchListener(object : OnSwipeTouchListener() {
override fun onSwipeLeft() {
Log.e("ViewSwipe", "Left")
}

override fun onSwipeRight() {
Log.e("ViewSwipe", "Right")
}
})

关于android - 通过使用 kotlin 向左或向右滑动来捕获事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49754979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com