Jetpack Compose Android Button长按检测失效问题求助
你遇到的问题确实是Button内部的点击逻辑优先消费了事件,导致外部的combinedClickable失效。要保留interactionSource且不自定义Button,可以通过监听interactionSource的交互流来实现长按检测,具体代码如下:
@Composable fun LongPressButtonDemo() { val interactionSource = remember { MutableInteractionSource() } val onClick = { println("按钮被点击") } val onLongClick = { println("按钮被长按") } Button( onClick = onClick, interactionSource = interactionSource ) { Text("长按测试按钮") } // 监听interactionSource的交互事件,捕获长按 LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> if (interaction is PressInteraction.LongPress) { onLongClick() } } } }
原理说明
Compose的interactionSource会对外暴露按钮的所有交互事件流,其中PressInteraction.LongPress就是系统判定长按触发时发出的事件。通过collect监听这个流,就能在不干扰Button原有点击逻辑的前提下,实现长按检测。这种方式既保留了interactionSource的使用,也无需自定义Button组件,完全符合你的需求。
内容的提问来源于stack exchange,提问作者kkkkk
相关产品推荐
相关产品推荐

