alfietap
alfietap

Reputation: 2253

Jetpack Compose focus requester not working with Dialog

I'm using the below code to try and request focus to a textfield and have the keyboard come up. Currently the textfield does request focus but the keyboard fails to show. This same code works in another project im working on, but the difference here is this code is inside a Dialog composable, and the other code isn't, so I'm not sure if its the Dialog making the keyboard fail to show?

val textField = remember { FocusRequester() }

 Dialog(onDismissRequest = {
    openDialog.value = false
    dialogInput.value = ""
}) {

    Column(
        modifier = Modifier
            .height(274.dp)
            .background(Color.Transparent)
            .clickable {
                openDialog.value = false
                dialogInput.value = ""
            }
    ) {

        OutlinedTextField(
            modifier = Modifier
                .height(64.dp)
                .background(Color.White)
                .focusRequester(textField),
            label = {
                Text(
                    text = label,
                    style = MaterialTheme.typography.body2.copy(color = Color.Black)
                )
            },
            value = dialogInput.value,
            onValueChange = {
                dialogInput.value = it
                events.filterPlayers(it)
            },
            textStyle = MaterialTheme.typography.body2.copy(color = Color.Black),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.White,
                unfocusedIndicatorColor = Color.White,
                focusedIndicatorColor = Color.White
            )
        )

        DisposableEffect(Unit) {
            textField.requestFocus()
            onDispose {}
        }
}

Upvotes: 13

Views: 5368

Answers (2)

LN-12
LN-12

Reputation: 1039

A more robust solution from https://issuetracker.google.com/issues/204502668 is the following which uses the LaunchedEffect side effect instead of just adding a listener in every recomposition:

val windowInfo = LocalWindowInfo.current

LaunchedEffect(windowInfo) {
    snapshotFlow { windowInfo.isWindowFocused }.collect { isWindowFocused ->
        if (isWindowFocused) {
            focusRequester.requestFocus()
        }
    }
}

Upvotes: 1

lllwwwbbb
lllwwwbbb

Reputation: 63

val focusRequester = FocusRequester()
LocalView.current.viewTreeObserver.addOnWindowFocusChangeListener {
    if (it) focusRequester.requestFocus()
}

this work for me, after window for dialog get focused, request focus for TextField would show soft keyboard automatically.

Upvotes: 6

Related Questions