【问题标题】:Android Edittext requestFocus() not working?Android Edittext requestFocus() 不工作?
【发布时间】:2019-01-01 18:28:10
【问题描述】:

我整天都在寻找,尝试了大多数已建立的解决方案,但仍然无法正常工作。 Android上有EditText的bug吗?

我有 2 个EditText 字段(致电edtA and edtB),edtA 是必填字段。当我将edtA留空并输入edtB,然后输入时,我希望它重新聚焦到edtA并显示错误弹出窗口“必填字段为空!”。

但是现在,edtB, edtA 中的光标仍然没有聚焦并显示错误popup

这是我在edtB 回车时的代码,edtNO_CON 是我上面提到的 edtA:

edtNO_CAR.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    if (TextUtils.isEmpty(mNoCon)) {
                        edtNO_CON.requestFocus();
                        edtNO_CON.setError(getString(R.string.error_field_required));
                    } else if (edtNO_CAR.getText().toString().trim().length() > 0) {
                        // Do something
                    }
                }
            }
            return true;
        }
    });

这是 edtA 的 XML:

<EditText
        android:id="@+id/confirmNO_CONTAINER"
        style="@style/text14Black"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.7"
        android:includeFontPadding="false"
        android:maxLines="1"
        android:singleLine="true" />

有人可以帮忙吗? 感谢您的宝贵时间。

更新: 在尝试了您的所有建议但没有任何改变后,我决定使用setOnEditorActionListener 而不是setOnKeyListener,现在它可以工作了! 这是我更新的代码:

edtNO_CAR.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT
                    || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                String strNoCon = edtNO_CON.getText().toString().trim();
                if (TextUtils.isEmpty(strNoCon)) {
                    edtNO_CON.requestFocus();
                    edtNO_CON.setError(getString(R.string.error_field_required));
                } else if (edtNO_CAR.getText().toString().trim().length() > 0) {
                    // Do something
                }
            }
            return true;
        }
    });

【问题讨论】:

  • 在你的xml文件中添加这个android:focusableInTouchMode="true"是为了授权焦点
  • 我试过了,没用:)

标签: android android-edittext


【解决方案1】:

先调用setEror再调用requestFocus

【讨论】:

    【解决方案2】:

    尝试添加以下 2 行:

    android:focusable="true" android:cursorVisible="true"

    如果它不起作用。请更新。

    【讨论】:

      【解决方案3】:

      只需在您的功能键监听器上使用 return@setOnKeyListener true

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2019-02-04
      • 2014-01-21
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多