默认焦点遍历顺序部分介绍了 Compose 如何自动为您的元素添加焦点遍历行为,包括一维(Tab
键)和二维(方向键)导航。在某些情况下,您可能需要覆盖此默认行为,并更明确地指定所需的遍历顺序。
覆盖一维遍历顺序
要更改一维导航的默认焦点遍历顺序,您需要创建一组引用,每个可获得焦点的可组合项一个引用
val (first, second, third, fourth) = remember { FocusRequester.createRefs() }
然后,使用 focusRequester
修饰符将它们中的每一个与一个可组合项关联起来
Column { Row { TextButton({}, Modifier.focusRequester(first)) { Text("First field") } TextButton({}, Modifier.focusRequester(third)) { Text("Third field") } } Row { TextButton({}, Modifier.focusRequester(second)) { Text("Second field") } TextButton({}, Modifier.focusRequester(fourth)) { Text("Fourth field") } } }
您现在可以使用 focusProperties
修饰符指定自定义遍历顺序
Column { Row { TextButton( {}, Modifier .focusRequester(first) .focusProperties { next = second } ) { Text("First field") } TextButton( {}, Modifier .focusRequester(third) .focusProperties { next = fourth } ) { Text("Third field") } } Row { TextButton( {}, Modifier .focusRequester(second) .focusProperties { next = third } ) { Text("Second field") } TextButton( {}, Modifier .focusRequester(fourth) .focusProperties { next = first } ) { Text("Fourth field") } } }
覆盖二维遍历顺序
还可以通过方向键对二维导航的焦点遍历顺序进行精细控制。对于每个元素,您可以通过添加 focusProperties
修饰符并指定向上、向下或任何其他方向的项来覆盖每个方向的默认导航目标
TextButton( onClick = {}, modifier = Modifier .focusRequester(fourth) .focusProperties { down = third right = second } ) {}
这种技术不仅能有效利用键盘方向键,也适用于有线和无线控制器上的方向键和摇杆。
为您推荐
- 注意:当 JavaScript 关闭时,会显示链接文本
- 更改焦点行为
- Compose 中的焦点