Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually move accessibility focus in Jetpack Compose

With Android View, I'm able to move the focus to a View like so:

fun View.requestAccessibilityFocus() {
    requestFocus()
    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
}

How do I achieve this in Jetpack Compose?

I tried using FocusRequester but it doesn't seem to do anything:

val lifecycleOwner = LocalLifecycleOwner.current
val requester = FocusRequester()

Box {
    ...
    Image(
        ...
        contentDescription = "My heading",
        modifier = Modifier
            ...
            .focusRequester(requester)
    )
}

DisposableEffect(lifecycleOwner) {
    val observer = LifecycleEventObserver { _, event ->
         if (event == Lifecycle.Event.ON_RESUME) {
             requester.requestFocus()
         }
    }
    lifecycleOwner.lifecycle.addObserver(observer)
    onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
like image 701
Fried Rice Avatar asked Apr 27 '26 03:04

Fried Rice


2 Answers

I had to add .focusable() and must do so after .focusRequester(focusRequester).

Box {
    ...
    Image(
        ...
        contentDescription = "My heading",
        modifier = Modifier
            ...
            .focusRequester(requester)
            .focusable()
    )
}
like image 57
Fried Rice Avatar answered Apr 28 '26 22:04

Fried Rice


This happens because DiposableEffect might be calling during recomposition. You should not request focus during composition. The solution I have found is to request a focus right after the composition. Like this

LaunchedEffect(Unit) {
        this.coroutineContext.job.invokeOnCompletion {
            focusRequester.requestFocus()
        }
    }

This makes sure your code will run when the LauchedEffect leaves the composition because it(the coroutine) either got canceled or completed.

like image 26
Nikhil Munna Avatar answered Apr 28 '26 23:04

Nikhil Munna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!