Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - onKeyEvent Modifier doesn't work in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As documentation of onKeyEvent says:

will allow it to intercept hardware key events when it (or one of its children) is focused.

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

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()
}

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...