如何在jetpack撰写中自动关注文本字段。当我单击文本字段并开始在其上键入时。同时,当我单击“后退”按钮时,然后当我尝试单击文本字段时,什么也没有发生。
val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
modifier = Modifier.fillMaxWidth(),
value = textState.value,
onValueChange = { value : TextFieldValue ->
textState.value = value
}
)
答案 0 :(得分:11)
发布问题的更新答案(API 在 Compose Beta 中重命名)
@Composable
fun AutoFocusingText() {
var value by mutableStateOf("Enter Text")
val focusRequester = remember { FocusRequester() }
TextField(
value = value,
onValueChange = { value = it },
modifier = Modifier.focusRequester(focusRequester)
)
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
}
答案 1 :(得分:3)
来自撰写单元测试,并应用于TextField Link
@ExperimentalFocus
@Composable
fun AutoFocusingText() {
val textState = remember { mutableStateOf(TextFieldValue()) }
val focusState = remember { mutableStateOf(FocusState.Inactive) }
val focusRequester = FocusRequester()
val focusModifier = Modifier.focus()
Row(
modifier = Modifier.focusObserver { focusState.value = it }
) {
val focusRequesterModifier = Modifier.focusRequester(focusRequester)
TextField(
modifier = focusModifier.then(focusRequesterModifier),
value = textState.value,
onValueChange = { value: TextFieldValue ->
textState.value = value
},
)
}
onActive {
focusRequester.requestFocus()
}
}
编辑:由于Box已在'1.0.0-alpha04'中弃用,因此将Box更改为Row
答案 2 :(得分:1)
使用 1.0.0-beta06
,您可以使用以下内容:
var text by remember { mutableStateOf("text") }
// initialize focus reference to be able to request focus programmatically
val focusRequester = FocusRequester()
Column {
TextField(
value = text,
onValueChange = {
text = it
},
label = { Text("label") },
modifier = Modifier
// add focusRequester modifier
.focusRequester(focusRequester)
)
然后使用 focusRequester.requestFocus()
。通过这种方式,系统将焦点授予与此 FocusRequester
关联的组件。
要在屏幕出现时自动聚焦该字段,您可以使用:
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
手动将焦点授予该字段:
Button(onClick = { focusRequester.requestFocus() }) {
Text("Click to give the focus")
}