DroidPest
DroidPest

Reputation: 394

Android Compose - Request Focus

Unable to gain focus on any compose component. It use to work in the project but after some gradle changes, only in some screens i can request focus. So i started a new project to test out the behavior in a clean environment. With this setup, onFocusChange gets the values "inactive" before requestFocus (which is correct) then changes to "deactivated", and after requestFocus, nothing. This is a new project with almost no code

@Composable
fun Greeting(name: String) {
    val focusRequester = remember { FocusRequester() }
    Button(
        onClick = {},
        modifier = Modifier
            .focusRequester(focusRequester = focusRequester)
            .onFocusChanged {
                it
            }
            .wrapContentSize()
        ,
    ) {
        Text(text = "Hello $name!")
    }
    LaunchedEffect(Unit) {
        this.coroutineContext.job.invokeOnCompletion {
            focusRequester.requestFocus()
        }
    }
}

And in my build.gradle, where compose_version = 1.1.1

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
    implementation 'androidx.activity:activity-compose:1.4.0'
}

Upvotes: 1

Views: 2592

Answers (1)

Richard Onslow Roper
Richard Onslow Roper

Reputation: 6863

You NEED to add the focusable modifier. It should come AFTER the onFocusChanged and focusRequestor Modifiers, and can also be replaced by focusTarget in some cases. See focusRequestor

Upvotes: 4

Related Questions