5

I have this TextFied Composable with both KeyboardOptions and KeyboardActions.

@Composable
fun TodoInputText(...) {
    val keyboardController = LocalSoftwareKeyboardController.current
    TextField( ....
        onValueChange = onTextChanged,
        keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(onDone = {
            onImeAction()
            keyboardController?.hide()
        }))}

The TextField is working with the Done Action but I need to disable Done ImeAction on the keyboard whenever the TextFied is empty as illustrated on this GIF

enter image description here

I have already extracted a state to check if the TextField is empty.

@Composable
fun TodoItemEntryInput(...) {

    //hold state for TextField
    val (text, setText) = remember { mutableStateOf("") }

    val isTextBlank = text.isNotBlank()

    //declare lambda function submit that handles  a submit event when done is pressed
    val submitAction = { .... }

    TodoItemInput(
        text = text,
        onTextChange = setText,
        submitAction = submitAction,
       
    )}

Now my question is how can I use the isTextBlank state to disable or Gray-out the Done ImeAction whenever the text is empty. This is to avoid bugs if the user enters blank text - I found input verification not very optimal for this case.

Tonnie
  • 4,865
  • 3
  • 34
  • 50

3 Answers3

3

This is impossible in regular Android, so with Jetpack Compose this task also cannot be solved.

All you can do is check if the text in the onDone callback is valid, continue if it is, and show an error if it is not.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
1

you can set IME action on text change of edit text

editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0) {
               editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
            } else {
               editText.setImeOptions(EditorInfo.IME_ACTION_NONE);
            }
        }
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113
0

I'm setting the imeAction to None if the value is not valid and to Done/Go if it is. Then plug the value into the keyboardOptions in the TextField

// setup the value
val imeAction = if (isValidInput(seekerInfoUiState.value)) {
    ImeAction.Done // or ImeAction.Go
} else {
    ImeAction.None
}

// plug the value and handle the action
TextField(
   keyboardOptions = KeyboardOptions(
    imeAction = imeAction,
   ),
   keyboardActions = KeyboardActions(
     onDone = { // or onGo
        /* do something when imeAction is clicked */
     }

   )
)

All the best...

Aakash
  • 21,375
  • 7
  • 100
  • 81