Request focus on TextField without opening keyboard

2 weeks ago 19
ARTICLE AD BOX

You can’t have focus and no keyboard by default easily, because this is a built in function, focus usually opens keyboard.

Explanation:

In Jetpack Compose, when a TextField gets focus, the keyboard opens automatically. In this code, I stop the keyboard from opening at first by setting LocalTextInputService to null. So the field gets focus, but no keyboard shows.

When the user taps on the field, keyboard is enabled again and focus is requested, so the keyboard opens at that time.

Why needed:

There is no direct way to keep focus without opening the keyboard in Compose. This approach helps avoid automatic keyboard popup and gives a smoother user experience.

But you can achieve using this code:

@Composable fun ChatScreen() { var fieldValue by remember { mutableStateOf("") } val focusRequester = remember { FocusRequester() } var enableKeyboard by remember { mutableStateOf(false) } LaunchedEffect(Unit) { focusRequester.requestFocus() } CompositionLocalProvider( LocalTextInputService provides if (enableKeyboard) LocalTextInputService.current else null ) { OutlinedTextField( value = fieldValue, onValueChange = { fieldValue = it }, modifier = Modifier .fillMaxWidth() .padding(top = 16.dp) .focusRequester(focusRequester) .pointerInput(Unit) { awaitPointerEventScope { while (true) { awaitPointerEvent() enableKeyboard = true focusRequester.requestFocus() } } } ) } }

I hope these suggestions will be helpful to you!!

Read Entire Article