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

Jetpack Compose中awaitCancellation()拦截软键盘失效问题求助

解决Jetpack Compose中InterceptPlatformTextInput拦截软键盘失效的问题

问题核心在于Activity内的输入法会话复用机制:当你先激活允许显示软键盘的输入框后,系统会维持一个活跃的输入法会话,此时切换到带拦截的输入框,单纯调用awaitCancellation()只能阻止新的输入法启动请求,但不会关闭已经活跃的会话,导致软键盘依然显示。

修复方案

在拦截不显示软键盘的分支中,先主动调用nextHandler.stopInputMethod()终止当前活跃的输入法会话,再执行awaitCancellation()阻止新的请求。

修改后的TestTextField代码如下:

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TestTextField(
    textFieldState: TextFieldState,
    showKeyboard: Boolean,
) {
    InterceptPlatformTextInput(interceptor = { request, nextHandler ->
        if (showKeyboard) {
            nextHandler.startInputMethod(request)
        } else {
            // 终止当前活跃的输入法会话,强制关闭软键盘
            nextHandler.stopInputMethod()
            awaitCancellation()
        }
    }) {
        BasicTextField(
            state = textFieldState,
            lineLimits = TextFieldLineLimits.SingleLine,
            textStyle = TextStyle(
                fontSize = 24.sp,
                letterSpacing = 2.sp,
                textAlign = TextAlign.Center,
                fontFamily = FontFamily.Monospace
            ),
            decorator = {
                Box(
                    modifier = Modifier
                        .padding(bottom = 10.dp)
                        .fillMaxWidth()
                        .height(50.dp)
                        .background(Color.White, RoundedCornerShape(10.dp))
                        .border(1.dp, Color.Gray, RoundedCornerShape(10.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    it()
                }
            }
        )
    }
}

原理说明

  • stopInputMethod()会主动断开当前的输入法连接,触发系统关闭软键盘;
  • awaitCancellation()则保持拦截状态,确保后续不会有新的输入法启动请求被处理;
  • 两者结合既关闭了已激活的软键盘,又阻止了新的唤起操作,完全实现预期的拦截效果。

内容的提问来源于stack exchange,提问作者Erick miguel costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:59:52