一、概念
不止触摸交互,在 ChromeOS 或外接键鼠的设备上,需要考虑焦点、悬停、右键等操作逻辑。
二、使用
2.1 焦点
使用 Tab 键来导航,改变边框以提供清晰的焦点指示器。
@Composable
fun Demo() {
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
val border = BorderStroke(
width = if (isFocused) 3.dp else 1.dp,
color = if (isFocused) Color.Red else Color.Black
)
Box(
modifier = Modifier
.focusable(interactionSource = interactionSource)
.border(border)
) {}
}
2.2 右键
右键/长按,表示更多选项。
@Composable
fun Demo() {
var showMore by rememberSaveable { mutableStateOf(false) }
var pressOffset by remember { mutableStateOf(DpOffset.Zero) }
Box(
modifier = Modifier.pointerInput(Unit) {
detectTapGestures(
onLongPress = { offset ->
pressOffset = DpOffset(offset.x.toDp(), offset.y.toDp())
showMore = true
}
)
}
) {
DropdownMenu(
expanded = showMore,
onDismissRequest = { showMore = false },
offset = pressOffset
) {
DropdownMenuItem(text = { Text("AAA") }, onClick = { })
DropdownMenuItem(text = { Text("BBB") }, onClick = { })
}
}
}
2.3 悬停
让组件感知鼠标悬停,改变背景色。
@Composable
fun Demo() {
val interactionSource = remember { MutableInteractionSource() }
val isHovered by interactionSource.collectIsHoveredAsState()
val backgroundColor = if (isHovered) Color.Gray else Color.White
Box(
modifier = Modifier
.hoverable(interactionSource = interactionSource)
.background(backgroundColor)
) { }
}
629

被折叠的 条评论
为什么被折叠?



