简单粗暴法
通过LocalSoftwareKeyboardController.current
获取SoftwareKeyboardController
对象,对软键盘进行显示与关闭操作
val keyboardController = LocalSoftwareKeyboardController.current
在最外层的组件中通过监听点击事件,执行键盘的关闭操作此方法存在一定弊端,谨慎使用
Box(
modifier = Modifier
.fillMaxSize()
.clickable {
keyboardController?.hide()
}
){
//your code
}
常规方法
val keyboardController = LocalSoftwareKeyboardController.current
val focusRequester = FocusRequester()
val focusManager = LocalFocusManager.current
通过pointerInput
监听单击点击事件,并清除当前聚焦组件的焦点
在文本编辑框TextField
中通过Modifier
完成对焦点请求和焦点变化的监听处理
Box(
modifier = Modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(onTap = {
focusManager.clearFocus()
})
}
){
TextField(
value = userTextStatus.text,
onValueChange = onChangeUser,
singleLine = true,
textStyle = TextStyle(color = MagicMusicTheme.colors.textContent, fontSize = 12.sp),//输入框内的字体样式
label = {
Text(text = userTextStatus.label, color = MagicMusicTheme.colors.textTitle, style = MaterialTheme.typography.body1)},//上方提示字体样式
placeholder = {
Text(text = userTextStatus.hint, color = MagicMusicTheme.colors.textContent, style = MaterialTheme.typography.caption)},//hint的字体样式
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
focusManager.clearFocus()
}),
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
.onFocusChanged {
if (!it.isFocused) {
keyboardController?.hide()
}
}
)
}