You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android自定义IME键盘切换输入框后删除键失效问题求助

问题修复方案

你的删除键代码存在两个核心问题:

  1. 只发送了KeyEvent.ACTION_DOWN事件,系统需要完整的**按下(DOWN)+抬起(UP)**事件对才能正确处理删除操作;
  2. 循环条件motionEvent.action == MotionEvent.ACTION_DOWN会导致无限循环(因为motionEvent的action不会在循环内改变),这会阻塞线程并导致InputConnection状态异常,切换输入框后问题会被放大。

另外,切换输入框后要确保获取的是当前激活输入框的InputConnection,避免使用缓存的旧连接。

修正后的代码示例:

"delete" -> {
    // 每次触发删除时,重新获取当前最新的InputConnection
    val currentInputConnection = (context as IMEService).currentInputConnection ?: return@yourFunction
    
    if (motionEvent.action == MotionEvent.ACTION_DOWN) {
        CoroutineScope(Dispatchers.Main).launch {
            // 处理单次删除:发送完整的DOWN+UP事件对
            currentInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
            currentInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
            
            // 处理长按持续删除:添加延迟避免过快触发,监听UP事件终止循环
            if (motionEvent.isLongPress) {
                while (motionEvent.action != MotionEvent.ACTION_UP) {
                    delay(100) // 可根据需求调整长按删除的间隔速度
                    currentInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                    currentInputConnection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
                }
            }
        }
    }
}

额外注意事项:

  • 确保IMEService在输入焦点切换时正确更新currentInputConnection,可通过重写onBindInput方法维护最新连接;
  • 所有InputConnection操作必须在主线程执行;
  • 长按逻辑需通过监听ACTION_UP事件终止循环,避免资源浪费。

内容的提问来源于stack exchange,提问作者Дмитрий Малигон

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:42:24