I want to implement a 4-digit PIN input. For each digit, I made a separate EditText. Accordingly, only one character can be written in one EditText. I need the focus to automatically move to the next EditText when entering a character, similarly for deletion. I tried to implement this with TextWatcher:

inner class EnterCodeTextWatcher(private var prevFocus: EditText?, private var nextFocus: EditText?) : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s.isNullOrEmpty() && prevFocus != null){ prevFocus?.requestFocus() prevFocus?.isCursorVisible = true } else if (!s.isNullOrEmpty() && nextFocus != null){ nextFocus?.requestFocus() nextFocus?.isCursorVisible = true } } } 

This works well if you type all 4 characters and delete all 4 characters. But if you enter only 2 characters and try to delete one character, it will not work, because the focus will be on the next EditText, which is empty. How to solve this problem? Or maybe you need to do it in another way?

1 answer 1

Maybe this will help you

  setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { if (getText().length() == 0 && previousView != null) { previousView.requestFocus(); } } return false; } }); 
  • That helped. But I noticed that on the emulator this function is not called when you click on the delete screen button. If you press on the keyboard, it works, it also works on my device with the MIUI firmware. You do not know what it can be connected with? - Evgeny Kurinnoy