Waqas Tahir
Waqas Tahir

Reputation: 8242

Jetpack Compose - Capture Key Event In Text Field

I want to create a text field inside a todo list where when the user presses backspace on an empty text field , it removes itself from the list , very simple to do as you can see !

Jetpack Compose , Core Text Field does not propogate its key events to parent composables / modifiers if the key event is editable ~~ written in their code

so I tried this and it does not work as expected

Modifier.onKeyEvent {
     Log.d("BL_KeyEvent",it.type.toString())
     if (it.key.keyCode == Key.Backspace.keyCode) {
           if (item.text.isEmpty()) {
              onBackspaceRemove()
           }
       }
       false
     }

I am just wondering how I could achieve it , since CoreTextField is internal and I have no way to capture key event in a text fielld

Upvotes: 11

Views: 8265

Answers (3)

Onatemowo Damilare
Onatemowo Damilare

Reputation: 55

Just change false to true. It should work.

Upvotes: 0

scottyab
scottyab

Reputation: 24039

Unsue if this has been fixed since you last tried @Waqas Tahir but I'm using ComposeUI v1.0.2 the following works for me:

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun aTextFieldWithOnBackspacePressedAction() {
    // this should be hoisted to ViewModel
    var text by remember { mutableStateOf("") }

    BasicTextField(
        value = text,
        // this also should be hoisted to ViewModel
        onValueChange = { text = it },
        modifier = Modifier
            .onKeyEvent { event: KeyEvent ->
                // handle backspace key
                if (event.type == KeyEventType.KeyUp &&
                    event.key == Key.Backspace &&
                    text.isEmpty()
                // also any additional checks of the "list" i.e isNotEmpty()
                ) {
                    // TODO remove from list
                    return@onKeyEvent true
                }
                false
            }
    )
}

Upvotes: 8

Richard Onslow Roper
Richard Onslow Roper

Reputation: 6817


@Composable
fun StackList(){
    var list = remember { mutableStateListOf<String>() } // This should be in your viewmodel
    LazyColumn{
        items(list){item ->
            var value by remember { mutableStateOf("") }
            TextField(
                modifier = Modifier.onKeyEvent {
                    Log.d("BL_KeyEvent",it.type.toString())
                    if (it.key.keyCode == Key.Backspace.keyCode) {
                        if (value.isEmpty()) {
                            list.remove(item)
                        }
                    }
                    false
                },
                value = value,
                onValueChange = {value = it}
            )
        }
    }
}

Upvotes: 1

Related Questions