如何以编程方式“按下软键盘按钮”

时间:2019-06-13 11:41:34

标签: android

我试图以编程方式在片段中“按下按钮”,但没有成功。

有什么想法吗?

这是我到目前为止尝试过的:

private fun pressKey(editText: View) {

        // Prepare a list of different events to test //

        val list = listOf(
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_NUMPAD_ENTER, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL),
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_NUMPAD_ENTER, 0, 0, 0, 0, KeyEvent.ACTION_UP),
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_NUMPAD_ENTER, 0, 0, 0, 0, KeyEvent.ACTION_DOWN),
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL),
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, KeyEvent.ACTION_UP),
                KeyEvent(0, 0, 0, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, KeyEvent.ACTION_DOWN),
                KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER),
                KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER),
                KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER),
                KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER),
                KeyEvent(KeyEvent.KEYCODE_ENDCALL, KeyEvent.KEYCODE_NUMPAD_ENTER),
                KeyEvent(KeyEvent.KEYCODE_ENDCALL, KeyEvent.KEYCODE_ENTER))

        val eventList = listOf(
                KeyEvent.KEYCODE_ENTER,
                KeyEvent.KEYCODE_NUMPAD_ENTER,
                KeyEvent.KEYCODE_ENTER)

        // Try each one of the events in a different way //

        list.forEach { activity!!.dispatchKeyEvent(it) }
        // similar to above
        list.forEach { view!!.dispatchKeyEvent(it) }
        // similar to above
        list.forEach { editText.dispatchKeyEvent(it) }

        ///////////////////////////////////////
        val inputConnectionEditText = BaseInputConnection(editText, true)
        list.forEach { inputConnectionEditText.sendKeyEvent(it) }
        // similar to above
        val inputConnection = BaseInputConnection(view!!, true)
        list.forEach { inputConnection.sendKeyEvent(it) }

        ///////////////////////////////////////
        val instrumentation = Instrumentation()
//      eventList.forEach { instrumentation.sendKeyDownUpSync(it) } // E/UncaughtException: java.lang.RuntimeException: This method can not be called from the main application thread
    }

谢谢。

离题:我被迫写更多的文字,否则我不允许发表,我希望帖子中有足够的信息,如果没有,请告诉我

0 个答案:

没有答案