Android Compose 如何delay一个事件
我们可以通过这几种方式Hander.postDelayed() CoroutineScope LaunchedEffect
- 通过rememberCoroutineScope(推荐)
val coroutineScope = rememberCoroutineScope() // in top of Composable
// ...
onTap = {
// Handle tap gesture on the key
isPopupVisible.value = true
coroutineScope.launch{
delay(250)
isPopupVisible.value = false
}
// ...
}
- 通过LaunchedEffect
Composable
fun PopupScreen(
label: String,
isVisible: Boolean,
onHide: () -> Unit
) {
val popupWidth = dimensionResource(id = R.dimen.key_width)
val popupHeight = dimensionResource(id = R.dimen.key_height)
val cornerSize = dimensionResource(id = R.dimen.key_borderRadius)
LaunchedEffect(Unit){
delay(250)
onHide()
}
// ...
}
在调用的 Composable 中,相应地对回调做出反应:onHide
if (key.shouldShowPopUp) {
// Display a pop-up screen if Clicked
PopupScreen(
label = popUpLabel,
isVisible = isPopupVisible.value,
onHide = { isPopupVisible.value = false }
)
}
https://developer.android.com/develop/ui/compose/side-effects
- handler(不推荐,有内存泄漏的风险)