I was searching for whole day, try most of solutions founded, but still not work. Is there a bug of EditText on Android?
I have 2 EditText fields (call edtA and edtB), edtA is required field. When I leave edtA blank and input to edtB, then Enter, I want it focus back to edtA and show error popup "Required field is empty!".
But now, the cursor stills in edtB, edtA is not focused and show error popup
Here is my code when edtB press Enter, edtNO_CON is edtA I mentioned above:
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;
}
});
And this is XML of edtA:
<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" />
Anyone can help? Thank for your time.
Update:
After tried all your suggestions but nothing changes, I decided to use setOnEditorActionListener instead of setOnKeyListener, and now it works!
Here is my updated code:
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;
}
});

