Android Edittext requestFocus()无法正常工作?

Android Edittext requestFocus() not working?

我整天都在搜索,尝试建立大多数解决方案,但仍然无法正常工作。 Android上是否存在EditText的错误?

我有2个EditText字段(称为edtA and edtB),edtA是必填字段。 当我将edtA留空并输入到edtB,然后按Enter时,我希望它集中到edtA并显示错误弹出窗口"必填字段为空!"。

enter image description here

但是现在,edtB, edtA中的光标静止不聚焦并显示错误popup

enter image description here

这是我的代码,当edtB按下Enter键时,我上面提到的edtNO_CON是edtA:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
3
4
5
6
7
8
9
<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,现在可以使用了!
这是我更新的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
        }
    });


这可以帮助您! 试试吧。 #回答


尝试添加以下两行:

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

如果不起作用。 请更新。


首先调用setEror,然后调用requestFocus