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

使用InputMethodService时Jetpack Compose视图无法更新问题

问题说明

按钮点击功能正常,但在使用InputMethodService时,Column内的Text组件显示/隐藏功能失效。该问题是在更新savedstate-ktx:1.2.0并使用setViewTreeSavedStateRegistryOwner()方法后出现的。

复现代码

自定义键盘Composable实现

@Composable
fun CustomKeyboard(imeService: MyIMEService) {

    var isShow by remember { mutableStateOf(true)}

    Column {

        if(isShow) { Text(text = "Good Luck", color = Color.Green) } // <- 此处功能失效!

        Button(onClick = {
            isShow = !isShow
            imeService.doSomethingWith("A")
        }) {
            Text(text = "Test Show/Hide")
        }
    }
}

InputMethodService完整实现代码

class ComposeKeyboardView(private val imeService: MyIMEService) : AbstractComposeView(imeService) {

    @Composable
    override fun Content() {
        CustomKeyboard(imeService)
    }
}


class MyIMEService : InputMethodService(), LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner {
    override fun onCreateInputView(): View {
        val view = ComposeKeyboardView(this)

        window!!.window!!.decorView.let { decorView ->
            ViewTreeLifecycleOwner.set(decorView, this)
            ViewTreeViewModelStoreOwner.set(decorView, this)
            decorView.setViewTreeSavedStateRegistryOwner(this)
        }
        return view
    }


    fun doSomethingWith(mData: String) {
        currentInputConnection?.commitText(mData, 1)
    }

    private val _lifecycleRegistry: LifecycleRegistry by lazy { LifecycleRegistry(this) }
    private val _store by lazy { ViewModelStore() }

    override fun getLifecycle(): Lifecycle = _lifecycleRegistry

    override fun getViewModelStore(): ViewModelStore = _store

    override val savedStateRegistry: SavedStateRegistry = SavedStateRegistryController.create(this).savedStateRegistry

    private fun handleLifecycleEvent(event: Lifecycle.Event) =
        _lifecycleRegistry.handleLifecycleEvent(event)

    @CallSuper
    override fun onCreate() {
        super.onCreate()
        // You must call performAttach() before calling performRestore(Bundle)
        savedStateRegistry.performAttach(lifecycle)
        savedStateRegistry.performRestore(null)
        handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
    }

    @CallSuper
    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        stopSelf()
    }

    @CallSuper
    override fun onDestroy() {
        super.onDestroy()
        handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }
}
背景补充

项目基于Stack Overflow社区中Yannick和Simsim的回答进行开发。

内容的提问来源于stack exchange,提问作者Swpan Datta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:05:23