我有一个可组合组件,如下所示:

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

当用户点击并持有Card时,我想判断用户是否持有了这张卡一秒钟.如果他们按住它超过一秒,那么我想记录"已点击",但如果他们在一秒前松开,则不要记录"已点击"

我怎样才能做到这一点呢?

推荐答案

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

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相关问答推荐

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

使函数同时挂起和取消挂起

Kotlin 中命名构造函数的惯用方式

创建包含 3 个相同项目的列表/使用返回类型重复

如何在 Kotlin 中为变量分配另一个变量的值?

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

如何在 Compose 中创建可重用的修饰符?

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

为什么 Kotlin 需要函数引用语法?

runOnUiThread 没有调用

Firestore - 如何在 Kotlin 中排除数据类对象的字段

封闭 lambda 的隐式参数被shadowed

从片段(fragment)中的点击事件启动协同程序

Kotlin 接口属性:只需要公共 getter 而没有公共 setter

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Android Jetpack导航,另一个主机片段中的主机片段

从命令行运行Java到Kotlin转换器?

如何在Android Studio 4.1中默认启用Kotlin Android扩展

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props