【发布时间】:2021-11-25 21:48:00
【问题描述】:
我正在使用 Jetpack Compose 构建我的 Android TV 应用,并尝试在一些 Text 组件上触发一些 onClick 事件。
我已经实现了Modifier.focusable,因此可以使用遥控器对其进行聚焦,并且我已经实现了Modifier.clickable,以便在单击组件时启动。
但是,当我在模拟器上启动应用程序时,我可以正确聚焦并选择组件,因为我可以看到背景颜色的变化,但是当按下我遥控器上的 OK 按钮(在我的例子中是KEYCODE_DPAD_CENTER)。但是,如果我在模拟器中用鼠标单击,则会触发该事件。
这是我的代码
@Composable
fun FocusablePill(text: String, focusRequester: FocusRequester = FocusRequester()) {
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
val isPressed by interactionSource.collectIsPressedAsState()
val color = if (isFocused || isPressed) action else lightTranslucent_10
val shape = RoundedCornerShape(CornerSize(24.dp))
Text(
text = text,
color = MaterialTheme.colors.onPrimary,
style = MaterialTheme.typography.button,
modifier = Modifier
.focusRequester(focusRequester)
.focusable(
interactionSource = interactionSource
)
.clickable(
interactionSource = interactionSource,
indication = null //this is just cosmetic, setting LocalIndication.current still doesn't work
) {
onCommandEntered(text)
}
.background(color, shape)
.padding(16.dp, 8.dp)
)
}
我也试过Modifier.selectable,但结果是一样的。事件仅在鼠标单击时触发。此外,使用 Button 组件也不起作用。
【问题讨论】:
-
感谢@PhilipDukhov,但在这种情况下,问题出在 onClick 事件上。焦点工作正常。
-
尝试使用
onKeyEvent修饰符,看看当你按下遥控键时它是否会给你任何事件。也许它被认为是键盘而不是鼠标。如果是这样,您可能需要[报告] (issuetracker.google.com/issues/new?component=612128)。 -
嗨@PhilipDukhov 我添加了onKeyEvent,现在我可以检查(it.type == KeyUp && it.key == Key.DirectionCenter)所以我可以执行我需要的任何操作,但我仍然找到了这个作为一种解决方法。我相信,因为我在 Android TV 上运行但在 ComposeActivity 中,而不是在“leanback 友好”片段中,所以按钮点击没有得到正确处理。但是,导航是。
-
我同意这是一种解决方法,let compose maintainers know 你期望什么行为。
-
@PhilipDukhov 完成。 issuetracker.google.com/issues/202171423谢谢!
标签: android-jetpack-compose android-tv