本文介绍了onKeyEvent 修饰符在 Jetpack Compose 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

return ComposeView(requireContext()).apply {
    setContent {
        Box(
            Modifier
                .onKeyEvent {
                    if (it.isCtrlPressed && it.key == Key.A) {
                        println("Ctrl + A is pressed")
                        true
                    } else {
                        false
                    }
                }
                .focusable()
        )
    }
}

为什么在使用平板电脑的硬件键盘时无法在片段中调用按键事件?

Why the key event cannot be called in fragment while using hardware keyboard of tablet?

推荐答案

作为 onKeyEvent 的文档说:

将允许它在它(或其子代之一)获得焦点时拦截硬件关键事件.

这意味着你需要让你的盒子聚焦,而不仅仅是聚焦.为此,您需要一个 FocusRequester,在我的示例中,我要求在视图呈现时获得焦点.在这篇文章

Which means you need to make your box focused, not just focusable. To do this you need a FocusRequester, in my example I'm asking focus when view renders. Check out more in this article

以后注意,如果用户点击文本字段,您的框将失去焦点,但是如果此文本字段在框中,onKeyEvent 仍然可以工作

For the future note, that if user taps on a text field, your box will loose focus, but onKeyEvent still gonna work if this txt field is inside the box

看起来空框无法聚焦,因此您需要使用修饰符添加一些大小.它仍然是隐形的:

Looks like empty box cannot become focused, so you need to add some size with a modifier. It still will be invisible:

val requester = remember { FocusRequester() }
Box(
    Modifier
        .onKeyEvent {
            if (it.isCtrlPressed && it.key == Key.A) {
                println("Ctrl + A is pressed")
                true
            } else {
                false
            }
        }
        .focusRequester(requester)
        .focusable()
        .size(10.dp)
)
LaunchedEffect(Unit) {
    requester.requestFocus()
}

或者只是将内容添加到 Box 中,这样它就会拉伸并且不再需要 .size 修饰符

Alternatively just add content to Box so it will stretch and .size modifier won't be needed anymore

此代码适用于我的蓝牙键盘 + android 智能手机,模拟器似乎无法识别

This code works fine with my Bluetooth keyboard + android smartphone, emulator seems not recognizing

这篇关于onKeyEvent 修饰符在 Jetpack Compose 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:42