https://kotlinlang.org logo
#compose
Title
# compose
m

Michal Klimczak

11/27/2023, 8:41 AM
is there a way to use a combination of regular TextField parameters to achieve the following: I need a screen with a single textfield which is going to be filled with a custom on-screen keyboard - no standard system ime. The problem is that I want a blinking cursor inside the textfield. readOnly would work great, however there is no blinking cursor since it's not really focused. Do i need to create a custom cursor for that?
a

Alexander Maryanovsky

11/27/2023, 9:47 AM
You can have the textfield be focused, and capture the events from its parent with
Modifier.onPreviewKeyEvent
m

Michal Klimczak

11/27/2023, 9:47 AM
In case anyone finds this in the future, here's what I used (with coments)
Copy code
Column {

        //hide the selection control (the little drop that let's user reposition the cursor)
        val customTextSelectionColors = TextSelectionColors(
            handleColor = Color.Transparent,
            backgroundColor = Color.Transparent
        )

        CompositionLocalProvider(
            LocalTextInputService provides null, //don't show keyboard
            LocalTextSelectionColors provides customTextSelectionColors
        ) {

            var phoneNumber by remember { mutableStateOf(TextFieldValue("")) }

            //request focus upon entering screen
            val focusRequester = remember { FocusRequester() }
            LaunchedEffect(Unit) {
                focusRequester.requestFocus()
            }

            BasicTextField(
                modifier = Modifier.background(Color.LightGray).focusRequester(focusRequester),
                value = phoneNumber,
                onValueChange = { },
            )

            Button(onClick = {
                val newText = phoneNumber.text + "1"
                phoneNumber = TextFieldValue(newText, TextRange(newText.length)) //use TextField so that the cursor position is updated along with the text
            }) {
                Text(text = "1")
            }
            Button(onClick = {
                val newText = phoneNumber.text.substring(0, max(phoneNumber.text.length - 1, 0))
                phoneNumber = TextFieldValue(newText, TextRange(newText.length))
            }) {
                Text(text = "<")
            }
        }
    }
❤️ 1
a

Alexander Maryanovsky

11/27/2023, 9:48 AM
Ah, wait, you just need your keyboard to not be focusable at all.
m

Michal Klimczak

11/27/2023, 9:48 AM
yeah, pasted the solution at the same time you wrote 🙂
a

Alexander Maryanovsky

11/27/2023, 9:50 AM
Use
Copy code
Modifier.focusProperties { 
        canFocus = true
    }
on the button