当用户点击Jetpack Compose系统中的UI元素(如点击项目列表)触发UI更改时,如何检测?是否可以使用Reactive Programming(如RxKotlin或RxJava)进行检测?
Jetpack Compose
UI
Reactive Programming
RxKotlin
RxJava
wwtsj6pe1#
您可以使用修饰符.clickable {}来检测对元素的单击
xhv8bpkk2#
这可以使用MutableInteractionSource以被动的方式完成。如果发出了触摸、拖动或悬停事件,你可以收集它们。Modifier.clickable发出按下事件。
@Composable private fun InteractionFlowExample() { Column( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { val interactionSource = MutableInteractionSource() val context = LocalContext.current LaunchedEffect(interactionSource) { interactionSource.interactions .onEach { interaction: Interaction -> if (interaction is PressInteraction.Press) { Toast.makeText( context, "Pressed", Toast.LENGTH_SHORT ).show() } else if (interaction is PressInteraction.Release) { Toast.makeText( context, "Released", Toast.LENGTH_SHORT ).show() } } .launchIn(this) } Box( Modifier .fillMaxWidth() .aspectRatio(4 / 3f) .border(2.dp, Color.Red) .clickable( interactionSource = interactionSource, indication = rememberRipple(), onClick = {} ), contentAlignment = Alignment.Center) { Text( text = "Collect Interactions", color = Color.White ) } } }
您还可以将互动添加到列表中,并像在正式文档中一样删除它们。
@Composable private fun CollectStatesExample() { val interactionSource = remember { MutableInteractionSource() } val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } is DragInteraction.Start -> { interactions.add(interaction) } is DragInteraction.Stop -> { interactions.remove(interaction.start) } is DragInteraction.Cancel -> { interactions.remove(interaction.start) } } } } val lastInteraction = when (interactions.lastOrNull()) { is DragInteraction.Start -> "Drag Start" is DragInteraction.Stop -> "Drag Stop" is DragInteraction.Cancel -> "Drag Cancel" is PressInteraction.Press -> "Pressed" is PressInteraction.Release -> "Press Release" is PressInteraction.Cancel -> "Press Cancel" else -> "No state" } Box( Modifier .fillMaxWidth() .border(2.dp, Blue400) .clickable( interactionSource, rememberRipple() ) {} .padding(8.dp) ) { Text(lastInteraction, modifier = Modifier.padding(8.dp)) } }
w8rqjzmb3#
modifier = Modifier .pointerInteropFilter { when(it.action ){ MotionEvent.ACTION_DOWN->{ Log.e("PIII","DOWN") //user press } MotionEvent.ACTION_UP->{ Log.e("PIII","UP") //user release } else->{ Log.e("PIII","Other") //other event } } true }
3条答案
按热度按时间wwtsj6pe1#
您可以使用修饰符.clickable {}来检测对元素的单击
xhv8bpkk2#
这可以使用MutableInteractionSource以被动的方式完成。如果发出了触摸、拖动或悬停事件,你可以收集它们。Modifier.clickable发出按下事件。
您还可以将互动添加到列表中,并像在正式文档中一样删除它们。
w8rqjzmb3#