我想在待办事项列表中创建一个文本字段,其中 when the user presses backspace on an empty text field , it removes itself
从列表中可以看出,做起来很简单!
Jetpack Compose ,如果关键事件是可编辑的,Core Text Field 不会将其关键事件传播给父可组合项/修饰符~~写在他们的代码中
所以我尝试了这个,但它没有按预期工作
Modifier.onKeyEvent {
Log.d("BL_KeyEvent",it.type.toString())
if (it.key.keyCode == Key.Backspace.keyCode) {
if (item.text.isEmpty()) {
onBackspaceRemove()
}
}
false
}
我只是想知道如何实现它,因为 CoreTextField 是内部的,我无法在文本字段中捕获关键事件
最佳答案
取消自您上次尝试 @Waqas Tahir 以来是否已解决此问题,但我使用的是 ComposeUI v1.0.2,以下对我有用:
@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
}
)
}
关于android - Jetpack Compose - 在文本字段中捕获关键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68861843/