[英]How to manage mouse right/center click with Jetpack Compose?
我找到了两种方法来为我工作。
首先是使用pointerInput
,你必须小心使用事件,否则它会被处理两次:
modifier = Modifier
.pointerInput(Unit) {
awaitPointerEventScope {
val event = awaitPointerEvent()
if (event.type == PointerEventType.Press &&
event.buttons.isSecondaryPressed) {
event.changes.forEach { e -> e.consume() }
// on-click logic here
}
}
}
其次是使用新的实验 API:
modifier = Modifier
.onClick(
matcher = PointerMatcher.mouse(PointerButton.Secondary),
onClick = {
// ...
}
)
在这两种情况下,我都有一些怪癖,其中按钮稍微处理按钮之外的事件,还有进一步的解决方法。
我设法找到了构建自定义修饰符的解决方案:
private fun Modifier.notifyRightClick(block: () -> Unit): Modifier =
composed {
val blockState = rememberUpdatedState(block)
pointerInput(Unit) {
while (currentCoroutineContext().isActive) {
awaitPointerEventScope {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.buttons.isSecondaryPressed) {
blockState.value()
}
}
}
}
}
如果在应用了修改器的 UI 元素上按下鼠标右键,这将执行作为block
传递的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.