开发中时常有搜索页的功能, 要求进入页面输入框自动获取光标并弹出软键盘. EditText的实现已经很成熟了, Compose如何实现呢? 先看下效果
效果
代码
val focusRequester = remember { FocusRequester() } //焦点
val softKeyboard = LocalSoftwareKeyboardController.current //软键盘
LaunchedEffect(Unit) {
delay(100) //延迟操作(关键点)
focusRequester.requestFocus()
softKeyboard?.show()
}
CustomTextField(
hint = "请输入关键字",
modifier = Modifier
.focusRequester(focusRequester)
.background(
color_form_enable,
shape = RoundedCornerShape(4.dp)
)
.height(40.dp)
.padding(start = 10.dp)
.weight(1f), text = ccc, leadingIcon = {
Icon(
modifier = Modifier.size(20.dp),
painter = painterResource(id = R.drawable.ic_baseline_search_24),
contentDescription = null
)
},
maxLines = 1,
onTextChange = {
mViewModel.filterKeyword(this)
}
)
分析
主要是 FocusRequester
和 LocalSoftwareKeyboardController
获取焦点和软键盘.
页面初始化的时候启动协程执行 requestFocus()
和 show()
的操作.
关键点是: delay(100)
协程的延迟操作, 主要是延迟执行 softKeyboard 的 show()
.
这样想要的效果就实现了.