gpt4 book ai didi

android - 在 Kotlin 中实现滑动手势

转载 作者:行者123 更新时间:2023-12-02 12:37:55 24 4
gpt4 key购买 nike

我正在尝试为我用 Kotlin 编写的应用程序实现手势检测器。我正在关注这个问题的评论:link

因此,我创建了 OnSwipeTouchListener 类并在我的类中实现了监听器:

class DetailActivity : AppCompatActivity() {

override fun onBackPressed() {
super.onBackPressed()
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.detail_activity)
window.decorView.setOnTouchListener(object: OnSwipeTouchListener(this@DetailActivity) {
override fun onSwipeLeft() {
onBackPressed()
}
override fun onSwipeRight() {
onBackPressed()
}
})
}

问题是它没有被识别,我没有得到任何错误。我试图放置一个 Log.i 来检查程序是否输入了两个覆盖方法,但没有打印任何内容。可以是 查看 问题?

编辑:这是监听器代码:
    open class OnSwipeTouchListener(ctx: Context) : OnTouchListener {

private val gestureDetector: GestureDetector

companion object {

private val SWIPE_THRESHOLD = 100
private val SWIPE_VELOCITY_THRESHOLD = 100
}

init {
gestureDetector = GestureDetector(ctx, GestureListener())
}

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

private inner class GestureListener : SimpleOnGestureListener() {


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

override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
var 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()
}
result = true
}
} else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom()
} else {
onSwipeTop()
}
result = true
}
} catch (exception: Exception) {
exception.printStackTrace()
}

return result
}


}

open fun onSwipeRight() {}

open fun onSwipeLeft() {}

open fun onSwipeTop() {}

open fun onSwipeBottom() {}
}

最佳答案

我试过你的代码是这样的:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main">

</androidx.constraintlayout.widget.ConstraintLayout>


main.setOnTouchListener(object: OnSwipeTouchListener(this@Main3Activity) {
override fun onSwipeLeft() {
onBackPressed()
}
override fun onSwipeRight() {
onBackPressed()
}
})

有用。可能问题是装饰 View

关于android - 在 Kotlin 中实现滑动手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60728621/

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