Compose 适配 - 键鼠模式

一、概念

不止触摸交互,在 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)
    ) { }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值