kotlin - JetPack 撰写 : Adding click duration

标签 kotlin android-jetpack-compose android-compose-card

我有一个像这样的可组合组件:

Card(
    modifier = Modifier
        .fillMaxWidth()
        .then(modifier ?: Modifier),
    backgroundColor = colorResource(id = R.color.Red),
    shape = RoundedCornerShape(percent = 50),
) {
    Row (
        modifier = Modifier
            .size(160.dp)
    ) {
    }
}

当用户单击并按住时,我想检查用户是否已按住卡一秒钟。如果他们按住它的时间超过一秒,那么我想记录“CLICKED”,但如果他们在一秒之前放手,那么就不要记录“CLICKED”

我怎样才能实现这个目标?

最佳答案

这可以通过编写自定义手势修饰符来完成,例如

fun Modifier.timedClick(
    timeInMillis: Long,
    interactionSource: MutableInteractionSource = remember {MutableInteractionSource()},
    onClick: (Boolean) -> Unit
) = composed {

    var timeOfTouch = -1L
    LaunchedEffect(key1 = timeInMillis, key2 = interactionSource) {
        interactionSource.interactions
            .onEach { interaction: Interaction ->
                when (interaction) {
                    is PressInteraction.Press -> {
                        timeOfTouch = System.currentTimeMillis()
                    }
                    is PressInteraction.Release -> {
                        val currentTime = System.currentTimeMillis()
                        onClick(currentTime - timeOfTouch > timeInMillis)
                    }
                    is PressInteraction.Cancel -> {
                        onClick(false)
                    }
                }

            }
            .launchIn(this)
    }

    Modifier.clickable(
        interactionSource = interactionSource,
        indication = rememberRipple(),
        onClick = {}
    )
}

使用

val context = LocalContext.current

Card(
    shape = RoundedCornerShape(percent = 50),
) {
    Box(
        modifier = Modifier
            .timedClick(
                timeInMillis = 1000,
            ) { passed: Boolean ->
                Toast
                    .makeText(
                        context,
                        "Pressed longer than 1000 $passed",
                        Toast.LENGTH_SHORT
                    )
                    .show()
            }
            .fillMaxWidth()
            .height(100.dp),
        contentAlignment = Alignment.Center
    ) {

        Text("Hello World")
    }
}

结果

enter image description here

关于kotlin - JetPack 撰写 : Adding click duration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73418606/

相关文章:

android - 如何禁用 FilledTextField 组件?

java - 使用 Kotlin 的 RSocket retrieveFlux()

android - kotlin-无法替换 RecyclerView 适配器中的 Fragment

android - 如何获取未缓存在 android 线圈中的新图像?

android - 如何使用jetpack compose为卡片 View 添加边框

android - Jetpack 撰写 ui : How to create cardview?

android - 如何在 Kotlin 中引用 "run"或 "apply"内的实现回调

Android 和 Kotlin 协程 : inappropriate blocking method call

android - 防止预览可组合项进入发布状态