android - JetPack Compose:执行 KeyBoardAction
问题描述
我正在使用撰写版本1.0.0-beta05
。ImeAction.Search
单击键盘图标时,我正在尝试执行搜索。我试着做如下。
TextField(
modifier = Modifier
.fillMaxWidth(.9f)
.padding(8.dp)
.background(MaterialTheme.colors.surface),
value = query,
onValueChange = { userInput ->
viewModel.onQueryChanged(userInput)
},
label = { Text(text = "Search") },
textStyle = TextStyle(color = MaterialTheme.colors.onSurface),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Search
),
leadingIcon = {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = null
)
},
onImeActionPerformed = { action, softKeyboardController ->
if (action == ImeAction.Search) {
viewModel.executeSearch(query)
softKeyboardController.hideSoftwareKeyboard()
}
},
)
但是,None of the following functiosn can be called with arguments suppplied.
我检查了一下,发现这onImeActionPerformed
不是TextField()
论点之一。所以我尝试使用 KeyBoardActions,如下所示:
TextField(
modifier = Modifier
.fillMaxWidth(.9f)
.padding(8.dp)
.background(MaterialTheme.colors.surface),
value = query,
onValueChange = { userInput ->
viewModel.onQueryChanged(userInput)
},
label = { Text(text = "Search") },
textStyle = TextStyle(color = MaterialTheme.colors.onSurface),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Search
),
leadingIcon = {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = null
)
},
keyboardActions = KeyboardActions(
onSearch = {
viewModel.executeSearch(query)
}
)
)
这是我的ViewModel
课
@HiltViewModel
class RecipeListViewModel @Inject constructor(
private val repository: RecipeRepository,
@Named("auth_token") private val authToken: String
) : ViewModel() {
val recipes: MutableState<List<Recipe>> = mutableStateOf(ArrayList())
val query = mutableStateOf("")
init {
executeSearch(query.value)
}
fun executeSearch(query: String) {
viewModelScope.launch {
val result = repository.search(
token = authToken,
page = 1,
query = "beef"
)
recipes.value = result
}
}
fun onQueryChanged(query:String){
this.query.value = query
}
}
我的目标是执行搜索和更新 UI。我被困在这里
解决方案
onImeActionPerformed
已弃用1.0.0-alpha12。
使用KeyboardActions
.
就像是:
val keyboardController = LocalSoftwareKeyboardController.current
keyboardActions = KeyboardActions(
onSearch = {
//...
keyboardController?.hide()
}
)
推荐阅读
- python - 从 Spyder 变量探索中删除默认变量
- react-native - 如何在 View React Native 中检测拖动端
- javascript - 如何在反应本机导航时覆盖 backButton 的行为
- python - 如何解决属性错误——张量流中没有属性“register_op_list”?
- node.js - socket.io 客户端无法可靠地连接/重新连接
- javascript - 在表情符号反应后无法让不和谐机器人分配角色
- algorithm - 荷兰国旗问题(但要用两种颜色)
- typescript - 我可以在安装后删除 typescript git clone 吗?
- regex - 如何在 Powershell 中使用 Select-String 匹配“foo”和“bar”?
- php - 升级到php8.0后,nginx仍然使用php7.2进行PHP-FPM