Hello guys, I am trying to implement TextField usi...
# compose
j
Hello guys, I am trying to implement TextField using
BasicTextField
and I want the content of the TextField to be highlighted when it receives focus. I am familiar with how to do it in XML but the I am stuck on how to implement it in compose. I'll appreciate any help. Thanks
m
Funny. I asked almost the same question here https://kotlinlang.slack.com/archives/C01D6HTPATV/p1682336482639329 just a couple of minutes earlier 😉.
o
I think you could achieve this with
TextFieldValue
and observing
InteractionSource
:
Copy code
var value by remember { mutableStateOf(TextFieldValue("")) }

val interactionSource = remember { MutableInteractionSource() }
LaunchedEffect(interactionSource) {
    interactionSource.interactions.collect {
        if (it is FocusInteraction.Focus) {
            val textSize = value.text.length
            value = value.copy(selection = TextRange(0, textSize))
        }
    }
}

BasicTextField(
    value = value,
    onValueChange = { value = it },
    interactionSource = interactionSource,
)
j
Thanks a bunch! I will check it out rn
@Oleksandr Balan Thanks. But the issue is that, if I use
focusRequester.requestFocus()
, it highlights. However, tapping on the textfield does not hightlight it
o
Huh, strange. Does your field is already focused when you tap on it? In that case it will not receive FocusInteraction I guess 🤔
j
No at all
o
I have forgot that
onFocusChanged
modifier exists, which was recommended here. Could you try it if it will work in your case?
j
Thanks a lot @Oleksandr Balan The initial solution worked but then, if input is selected, I cannot move the cursor as it is stuck at the start position
o
move the cursor
Do you mean to un-focus the input field? Or move it with drag-n-drop? To un-focus I have used custom modifier on outer Box:
Copy code
fun Modifier.clearFocusOnTap(): Modifier = composed {
    val focusManager = LocalFocusManager.current
    Modifier.pointerInput(Unit) {
        detectTapGestures(
            onTap = { focusManager.clearFocus() }
        )
    }
}
Like this:
Copy code
Box(
    contentAlignment = Alignment.Center,
    modifier = Modifier
        .fillMaxSize()
        .imePadding()
        .clearFocusOnTap()
) {
    ...
}
But moving with drag-n-drop works fine for me, see the video.
j
@Oleksandr Balan I finally got it right thanks to you.