首页 > 解决方案 > 我需要从 onTouchEvent 中删除 TAP_TIMEOUT 延迟

问题描述

我正在开发一个在触摸按钮时需要精确度的项目。意思是,在按钮被触摸的那一刻,ACTION_DOWN 中的某些代码必须立即执行。

我发现实际上有一个预期的 PREPRESSED 状态将代码延迟指定的时间间隔。在MotionEvent.ACTION_DOWN中使用访问此间隔ViewConfiguration.getTapTimeout()。此延迟的目的是确定用户是否正在点击或滚动。https://developer.android.com/reference/android/view/ViewConfiguration.html#getTapTimeout()

需要消除这种滞后。

在此线程中对此进行了更多讨论:如何使按钮更具响应性?

一些用户建议可以通过扩展 Button 类并覆盖 onTouchEvent 来删除它。

我试图扩展一个 Button 类,但是,我不知道如何将这个 getTapTimeout 更改为 0ms。

这是我的进展:

class NoLagButton : Button {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) isPressed = true
        println(ViewConfiguration.getTapTimeout())
        ViewConfiguration.getTapTimeout()
        return super.onTouchEvent(event)
    }

}

通过使用扩展NoLagButton,如何将 getTapTimeout 的长度修改为 0?

标签: androidbuttonkotlinlagmotionevent

解决方案


你不能改变ViewConfiguration.getTapTimeout()没有反射黑客的价值。您的解决方案有任何问题吗?

override fun onTouchEvent(event: MotionEvent): Boolean {
    if (event.action == MotionEvent.ACTION_DOWN) {
        // code here will run instantly without delay
    }
    return super.onTouchEvent(event)
}

推荐阅读