Search code examples
android-jetpack-composeandroid-jetpackandroid-compose-textfield

How to open a BasicTextField focused with blinking cursor in it?


I have a BasicTextField in one of my views. I am showing the soft keyboard by default and when I start typing letters on the keyboard, nothing is shown in the BasicTextField, since it has no cursor.

To make my keyboard actions visible, I have to tap into the TextField, to make the cursor visible. Now, whenI tap on the keyboard, I see the result in the BasicTextField.

How can I open the BasicTextField with an active blinking cursor in it?

EDIT: the proposed solution from here did not work for me

val focusRequester = FocusRequester()
val keyboardController = LocalSoftwareKeyboardController.current

//..

    .focusRequester(focusRequester)
    .onFocusChanged {
        if (it.isFocused) {
            keyboardController?.show()
        }
    }

Did neither activated the cursor nor made the keyboard appear. In addition to that

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

leads to a crash:

java.lang.IllegalStateException: FocusRequester is not initialized. Here are some possible fixes:

   1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
   2. Did you forget to add a Modifier.focusRequester() ?
   3. Are you attempting to request focus during composition? Focus requests should be made in
   response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }

    at androidx.compose.ui.focus.FocusRequester.requestFocus(FocusRequester.kt:54)

Solution

  • I got it working:

    val focusRequester = FocusRequester()
    
    //..
    
    .focusRequester(focusRequester)
    

    and instead of

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

    I used

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }