Compose Modifier

requestFocusOnHierarchyActive

This Modifier is used in conjunction with hierarchicalFocusGroup and will request focus on the following focusable element when needed (i.e.

HierarchicalFocusSample

@Sampled
@Composable
fun HierarchicalFocusSample() {
    var selected by remember { mutableIntStateOf(0) }

    Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
        repeat(5) { colIx ->
            Box(
                Modifier.hierarchicalFocusGroup(active = selected == colIx)
                    .weight(1f)
                    .clickable { selected = colIx }
                    .then(
                        if (selected == colIx) {
                            Modifier.border(BorderStroke(2.dp, Color.Red))
                        } else {
                            Modifier
                        }
                    )
            ) {
                // This is used to add a Gray background to the currently focused item, as seen by
                // the focus system.
                var focused by remember { mutableStateOf(false) }

                BasicText(
                    "$colIx",
                    style =
                        TextStyle(
                            color = Color.White,
                            fontSize = 20.sp,
                            textAlign = TextAlign.Center,
                        ),
                    modifier =
                        Modifier.fillMaxWidth()
                            .requestFocusOnHierarchyActive()
                            .onFocusChanged { focused = it.isFocused }
                            .focusable()
                            .then(
                                if (focused) {
                                    Modifier.background(Color.Gray)
                                } else {
                                    Modifier
                                }
                            ),
                )
            }
        }
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: