您可以Modifier.pointerInpteropFilter
为此使用:
var job by remember {
mutableStateOf<Job?>(null)
}
val scope = rememberCoroutineScope()
Icon(
imageVector = Icons.Filled.Favorite,
modifier = Modifier
.requiredSize(96.dp)
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
job = scope.launch {
while (true) {
// trigger event
Log.d("foo", "Trigger event")
delay(500L)
}
}
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
job?.cancel()
job = null
}
}
true
},
contentDescription = "Sample icon"
)
另一种解决方案是使用Modifier.pointerInput
:
val scope = rememberCoroutineScope()
Icon(
imageVector = Icons.Filled.Favorite,
modifier = Modifier
.requiredSize(96.dp)
.pointerInput(Unit) {
while (true) {
awaitPointerEventScope {
awaitFirstDown()
val job = scope.launch {
while (true) {
// trigger event
Log.d("foo", "Trigger event")
delay(500L)
Log.d("foo", "After delay")
}
}
waitForUpOrCancellation()
job.cancel()
}
}
},
contentDescription = "Sample icon"
)