Focus a Text composable

Viewed 165

I need to make a custom text editor composable with some custom behavior and appearance that should be quite different from a TextField composable, so I'm starting from a Text composable instead.

I encounter two problems: I cannot manage to open the keyboard when clicking on the composable. And don't manage to have the Text get the focus. I believe that the later is the reason to the former.

Here is a simplified version of the composable:

@ExperimentalComposeUiApi
@Composable
fun FocusText(
    modifier: Modifier,
    text: String
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusRequester = remember { FocusRequester() }

    Text(
        text = text,
        modifier = modifier
            .focusable(true)
            .focusModifier()
            .focusRequester(focusRequester)
            .onFocusChanged { it: FocusState ->
                println("xxx onFocusChanged: $it")
            }
            .clickable {
                println("xxx onClick")
                focusRequester.requestFocus()
                keyboardController?.show()
            }
    )
}

Despite having both .focusable(true) and .focusModifier() and calling requestFocus() in onClick(), the composable doesn't get the focus when clicking on it. Also, the keyboard doesn't get opened.

What am I doing wrong?

1 Answers

You can use a BasicTextField instead of a Text.
It is basically an EditText via hardware or software keyboard, without decoration hint or placeholder. Of course you can add it.

Something like:

var value by rememberSaveable { mutableStateOf("edit text") }

BasicTextField(
    value = value,
    onValueChange = { value = it }
)
Related