New Compose Multiplatform components arrived on Composables UICheck it out →

Modifier in Compose Ui

focusRestorer

Common

This modifier can be used to save and restore focus to a focus group. When focus leaves the focus group, it stores a reference to the item that was previously focused. Then when focus re-enters this focus group, it restores focus to the previously focused item.

Last updated:

Installation

dependencies {
   implementation("androidx.compose.ui:ui:1.7.0-beta04")
}

Overloads

@ExperimentalComposeUiApi
fun Modifier.focusRestorer(
    onRestoreFailed: (() -> FocusRequester)? = null
)

Parameters

namedescription
onRestoreFailedcallback provides a lambda that is invoked if focus restoration fails. This lambda can be used to return a custom fallback item by providing a [FocusRequester] attached to that item. This can be used to customize the initially focused item.

Code Examples

FocusRestorerSample

@Composable
@Sampled
@OptIn(ExperimentalComposeUiApi::class
fun FocusRestorerSample() {
    LazyRow(Modifier.focusRestorer()) {
        item { Button(onClick = {}) { Text("1") } }
        item { Button(onClick = {}) { Text("2") } }
        item { Button(onClick = {}) { Text("3") } }
        item { Button(onClick = {}) { Text("4") } }
    }
}

FocusRestorerCustomFallbackSample

@Composable
@Sampled
@OptIn(ExperimentalComposeUiApi::class
fun FocusRestorerCustomFallbackSample() {
    val focusRequester = remember { FocusRequester() }
    LazyRow(
        // If restoration fails, focus would fallback to the item associated with focusRequester.
        Modifier.focusRestorer { focusRequester }
    ) {
        item {
            Button(
                modifier = Modifier.focusRequester(focusRequester),
                onClick = {}
            ) { Text("1") }
        }
        item { Button(onClick = {}) { Text("2") } }
        item { Button(onClick = {}) { Text("3") } }
        item { Button(onClick = {}) { Text("4") } }
    }
}