android 如何在TextField为空时禁用软键盘上的ImeAction/按钮

bbmckpt7  于 2023-06-27  发布在  Android
关注(0)|答案(3)|浏览(103)

我有一个TextFied Composable,包含KeyboardOptionsKeyboardActions

  1. @Composable
  2. fun TodoInputText(...) {
  3. val keyboardController = LocalSoftwareKeyboardController.current
  4. TextField( ....
  5. onValueChange = onTextChanged,
  6. keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
  7. keyboardActions = KeyboardActions(onDone = {
  8. onImeAction()
  9. keyboardController?.hide()
  10. }))}

TextField与Done Action一起工作,但每当TextField为空时,我需要禁用键盘上的Done ImeAction,如此GIF所示

我已经提取了一个状态来检查TextField是否为空。

  1. @Composable
  2. fun TodoItemEntryInput(...) {
  3. //hold state for TextField
  4. val (text, setText) = remember { mutableStateOf("") }
  5. val isTextBlank = text.isNotBlank()
  6. //declare lambda function submit that handles a submit event when done is pressed
  7. val submitAction = { .... }
  8. TodoItemInput(
  9. text = text,
  10. onTextChange = setText,
  11. submitAction = submitAction,
  12. )}

现在我的问题是,当文本为空时,如何使用isTextBlank状态来禁用或灰显Done ImeAction。这是为了避免用户输入空白文本时的错误--我发现输入验证对于这种情况不是很理想。

91zkwejq

91zkwejq1#

您可以设置输入法的行动对文本的更改编辑文本

  1. editText.addTextChangedListener(new TextWatcher() {
  2. @Override
  3. public void onTextChanged(CharSequence s, int start, int before, int count) {
  4. if (s.length() > 0) {
  5. editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
  6. } else {
  7. editText.setImeOptions(EditorInfo.IME_ACTION_NONE);
  8. }
  9. }
ztyzrc3y

ztyzrc3y2#

如果值无效,我将imeAction设置为None,如果值有效,则设置为Done/Go。然后将该值插入TextField中的keyboardOptions

  1. // setup the value
  2. val imeAction = if (isValidInput(seekerInfoUiState.value)) {
  3. ImeAction.Done // or ImeAction.Go
  4. } else {
  5. ImeAction.None
  6. }
  7. // plug the value and handle the action
  8. TextField(
  9. keyboardOptions = KeyboardOptions(
  10. imeAction = imeAction,
  11. ),
  12. keyboardActions = KeyboardActions(
  13. onDone = { // or onGo
  14. /* do something when imeAction is clicked */
  15. }
  16. )
  17. )

祝你一切顺利

展开查看全部
ffvjumwh

ffvjumwh3#

这是常规Android中的impossible,因此使用Jetpack Compose也无法解决此任务。
您所能做的就是检查onDone回调中的文本是否有效,如果有效则继续,如果无效则显示错误。

相关问题