Home > front end >  Android: enter or tab keys still enters values into the password input field using jetpack compose
Android: enter or tab keys still enters values into the password input field using jetpack compose

Time:09-19

When I enter or tab keys still enters values into the password input field using jetpack compose.

Below is my code snippet:

val (focusRequester) = FocusRequester.createRefs()

TextField(
    value = text,
    onValueChange = {
        text = it
    },
    singleLine = true,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
    keyboardActions = KeyboardActions(
        onDone = { focusRequester.requestFocus() }
    ),
    modifier = Modifier.onKeyEvent {
        if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER){
            focusRequester.requestFocus()
            true
        }
        false
    }
)

Tab key and enter key entries from laptop keyboard via Vysor not from android keyboard.

Any suggestions are welcome here. Thanks!

Update 1:

Is there any way we can do for all the function keys like standards, with out using below code.

modifier = Modifier.onKeyEvent {
        if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER || it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_TAB) {
           focusManager.moveFocus(FocusDirection.Next)
      }
        false
    }

CodePudding user response:

You can use a regex, something like:

 val pattern = remember { Regex("^[^\\t\\n]*\$") }

 TextField(
        value = text,
        onValueChange = {
            if (it.isEmpty() || it.matches(pattern)) {
                text = it
            }
        },
        singleLine = true,
        maxLines= 1,
        //
   )

CodePudding user response:

I think it should help you to clear focus after clicking on keyboard Done button.

val focusManager = LocalFocusManager.current

TextField(
    value = text,
    onValueChange = {
       text = it
    },
    singleLine = true,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
    keyboardActions = KeyboardActions(
       onDone = { focusManager.clearFocus() }
    ),
)

CodePudding user response:

val (focusRequester) = FocusRequester.createRefs()

TextField(
    value = text,
    onValueChange = {
            if (it.isEmpty() || it.matches(pattern)) {
                text = it
            }
        },
    singleLine = true,
    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
    keyboardActions = KeyboardActions(
        onDone = { focusRequester.requestFocus() }
    ),
    modifier = Modifier.onKeyEvent {
        if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER || it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_TAB) {
           focusManager.moveFocus(FocusDirection.Next)
      }
        false
    }
)
  • Related