requestInitialFocus
Utility Modifier to request focus on initial layout. This Modifier calls to onRequestFocus when onGloballyPositioned is set, caching the fact it has been positioned to make sure any request to onRequestFocus is only called once after positioning.
This can be used on a focusGroup or on any focusable composable.
Since
0.3.0
Example:
Box(
modifier = Modifier
.fillMaxSize()
.focusGroup()
.requestInitialFocus(),
) {
repeat(20) {
Button(onClick = onClick) {
BasicText("Clickable")
}
}
}
Example custom onRequestFocus callback.
Box(
modifier = Modifier
.fillMaxSize()
.focusGroup()
.requestInitialFocus {
delay(1000)
if (somethingIsNotRight) {
// Return CancelFocusRequest to veto the call to requestFocus().
return@requestInitialFocus Cancel
}
},
) {
repeat(20) {
Button(onClick = onClick) {
BasicText("Clickable")
}
}
}
Parameters
Whether or not the request to focus should be enabled. Toggling enabled will treat it like the modifier has only just been applied and cause onRequestFocus to be called again. You can safely use this as a means to re-request focus.
Optional suspending callback to add your own custom handling for requesting focus. When providing onRequestFocus, the requestFocus call will happen after the the callback completes. to cancel/veto the request to focus you can return RequestFocusModifierScope.Cancel within the onRequestFocus block.
Note: When using lazy layouts you will need to wait for the children of the lazy to be laid out first otherwise items will not be ready to focus. You can use the enabled flag or custom onRequestFocus callback to help delay and wait for the lazy items to be visible. Alternatively you can just add your own logic to request focus to the specific item you would like to request focus for as it is laid out in the lazy layout.