You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose Android Button长按检测失效问题求助

Jetpack Compose 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:42:39