1

I am trying to create a fully custom TextField in Android using Jetpack compose

everything is ok with the hardware keyboard but the soft keyboard is not opening

this is how I start: (with simple code)


@Composable
fun MyCustomTextField() {
    var text by remember { mutableStateOf("") }
    val focusRequester = remember { FocusRequester() }
    val keyboardController = LocalSoftwareKeyboardController.current
    var hasFocus by remember { mutableStateOf(false) }


    Box(
        modifier = Modifier
            .focusRequester(focusRequester)
            .onFocusChanged { hasFocus = it.hasFocus }
            .focusable()
            .focusTarget()
            .clickable {
                // Request focus and show keyboard when clicked
                if (!hasFocus) {
                    focusRequester.requestFocus()
                } else {
                    keyboardController?.show()
                }
            }
            .onKeyEvent {
                if (it.type == KeyEventType.KeyDown) {
                    if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_DEL) {
                        if (text.isNotEmpty()) {
                            text = text.substring(0, text.length - 1)
                        }
                    } else {
                        text += it.nativeKeyEvent.unicodeChar
                            .toChar()
                            .toString()
                    }
                }
                false
            }
    )
    {
        Text("text:" + text)
    }


    // Request focus when the composable enters the composition
    LaunchedEffect(hasFocus) {
        focusRequester.requestFocus()
        keyboardController?.show()
    }
}
2
  • Try this LaunchedEffect(hasFocus) { if (hasFocus) { keyboardController?.show() } } Commented Jun 28, 2024 at 11:12
  • I tried this too. not worked Commented Jun 29, 2024 at 11:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.