我使用this answer成功地实现了在Advanced Webview上检测滑动手势的功能。然而,一旦我实现了这个功能,webview 上的滑动手势就一直在大致滚动。所以我希望能像以前一样顺利完成。
这是我的代码。
OnSwipeWebviewTouchListener.kt
class OnSwipeWebviewTouchListener(ctx: Context?, touchListener: TouchListener) : View.OnTouchListener {
private val gestureDetector: android.view.GestureDetector
init {
gestureDetector = GestureDetector(ctx, GestureListener(touchListener))
}
override fun onTouch(v: View?, event: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(event)
}
private inner class GestureListener internal constructor(touchListener: TouchListener) : GestureDetector.SimpleOnGestureListener() {
private val touchListener: TouchListener
init {
this.touchListener = touchListener
}
override fun onDown(e: MotionEvent): Boolean {
return false // THIS does the trick
}
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)) {
// You can customize these settings, so 30 is an example
if (Math.abs(diffX) > 30 && Math.abs(velocityX) > 30) {
if (diffX > 0) {
touchListener.onSwipeRight()
} else {
touchListener.onSwipeLeft()
}
result = true
}
} else if (Math.abs(diffX) < Math.abs(diffY)) {
if (Math.abs(diffY) > 30 && Math.abs(velocityY) > 30) {
if (diffY > 0) {
touchListener.onSwipeDown()
} else {
touchListener.onSwipeUp()
}
result = true
}
} else {
result = false
}
} catch (exception: Exception) {
exception.printStackTrace()
}
return result
}
}
}
interface TouchListener {
fun onSwipeLeft() {
Timber.d("Swipe left")
}
fun onSwipeRight() {
Timber.d("Swipe right")
}
fun onSwipeUp() {
Timber.d("Swipe up")
}
fun onSwipeDown() {
Timber.d("Swipe Down")
}
}
WebViewActivity.kt
class WebViewActivity : AppCompatActivity(), AdvancedWebView.Listener, TouchListener {
...
override fun onCreate(savedInstanceState: Bundle?) {
...
setSupportActionBar(binding.tbWebview)
binding.wvLoadWebsite.setOnTouchListener (OnSwipeWebviewTouchListener(this@WebViewActivity, this@WebViewActivity))
}
override fun onSwipeDown() {
super.onSwipeDown()
if (supportActionBar == null)
return
supportActionBar?.let {
if (!it.isShowing) {
it.show()
}
}
}
override fun onSwipeUp() {
super.onSwipeDown()
if (supportActionBar == null)
return
supportActionBar?.let {
if (it.isShowing) {
it.hide()
}
}
}
}
以防万一,我正在使用 NoActionbar 主题并添加了 androidx.appcompat.widget.Toolbar
如果有人能帮助解决我的问题,我将不胜感激。
我在this answer上找到了解决方案。显示/隐藏工具栏效果很好,同时滚动也很流畅。
注意“CustomeGestureDetector”上的拼写错误。在我链接的答案中应该是“CustomGestureDetector”。