onKeyListener / dispatchKeyEvent与Edittext和键盘侦听器的错误行为

时间:2018-10-16 16:11:43

标签: android android-edittext android-softkeyboard keylistener

我有一个EditText,在其中实现了一个侦听器,以了解退格何时向下/向上

但是听者的行为很奇怪。

当我按住软键盘上的任意键时,会依次调用“向下”和“向上”键,但是只有当我松开该键时才会如此。

当我按住退格键时,即使我仍然按下该键,也会多次调用上/下键。

我使用日志来检查行为。参见下面的代码:

    myEditText.setOnKeyListener { v, keyCode, event ->


        if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {

            if (event.action == KeyEvent.ACTION_UP) {
                Log.wtf("delete", "up")

            }

            if (event.action == KeyEvent.ACTION_DOWN) {
                Log.wtf("delete", "down")
            }


        } else {

            if (event.action == KeyEvent.ACTION_UP) {
                Log.wtf("another ", "up")

            }

            if (event.action == KeyEvent.ACTION_DOWN) {
                Log.wtf("another", "down")
            }

        }

        true

    }
}

按住空格键时的日志:

E/delete: down
E/delete: up
E/delete: down
E/delete: up
E/delete: down
E/delete: up
E/delete: down
E/delete: up

按下另一个键并释放时的日志

E/another: down
E/another: up

当我从活动覆盖 dispatchKeyEvent()时,我会遇到相同的错误。

override fun dispatchKeyEvent(event: KeyEvent): Boolean {

    if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {

        if (event.action == KeyEvent.ACTION_UP) {
            Log.wtf("delete", "up")

        }

        if (event.action == KeyEvent.ACTION_DOWN) {
            Log.wtf("delete", "down")
        }


    } else {

        if (event.action == KeyEvent.ACTION_UP) {
            Log.wtf("another ", "up")

        }

        if (event.action == KeyEvent.ACTION_DOWN) {
            Log.wtf("another", "down")
        }

    }

    return true

}

这是正确的行为吗?仅当我按下并释放按钮时,事件才会触发吗?

0 个答案:

没有答案