restoreChildFocus

fun Modifier.restoreChildFocus(onRestoreFailed: () -> FocusRequester? = null): Modifier

Utility Modifier to restore focus of a child within a focus group. A common use case is to restore the last focus child when navigating from a nested LazyRow within a LazyColumn.

This Modifier also applies focusGroup and focusRestorer.

Since

0.3.0

Example:

LazyColumn {
items(20) {
LazyRow(
modifier = Modifier
.fillMaxSize()
.restoreChildFocus()
) {
items(100) {
Button(onClick = onClick) {
BasicText("Clickable")
}
}
}
}
}

Example focusing the first item in a lazy row:

LazyColumn {
items(20) {
val rowFirstItemRequester = remember { FocusRequester() }

LazyRow(
modifier = Modifier
.fillMaxSize()
// Use restore failed to only request focus to the first item
// if restoring previous focused item fails.
.restoreChildFocus(onRestoreFailed = { rowFirstItemRequester })
) {
items(100) { index ->
// Only add the focus requester if it is the first item in the row.
Button(
modifier = Modifier.thenIf(
index == 0,
ifTrueModifier = Modifier.focusRequester(rowFirstItemRequester),
),
onClick = onClick,
) {
BasicText("Clickable")
}
}
}
}
}

Parameters

onRestoreFailed

A callback if focus restoration fails within the applied focusRestorer.