There is a numeric EditText maximum length of 2 characters, the default value is 00. With the help of TextWatcher, you get to track character input, but if the maximum length is reached nothing happens. How can I replace the old value with a new one?

  • It's not very clear what your problem is. Do you want the subsequent button presses (third and so on) to score the two numbers already entered, for example, by pressing the 1 2 3 4 buttons in sequence, the input field should remain 34? - pavlofff
  • one
    Yes exactly. This is implemented in the standard timer - Doom

2 answers 2

final EditText et = (EditText)findViewById(R.id.et); et.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if(et.getText().length()==2) et.setSelection(0,2); return false; } }); 

When two digits are entered, they are immediately highlighted and if you continue typing, they will be replaced with new ones. I understood correctly, do you need this?

  • Not really. I have this code works only by pressing the OK button. Introduced new values ​​pressed ok the keyboard disappeared, the text is highlighted, but if you press again on editing, the selection is removed - Doom
  • @Doom, so now you need to select text in it when you click on EditText? Like in Chrome, in the address bar? - Flippy
  • Yes. Do not tell me if it is possible to disable the selection visualization? - Doom
  • @Doom, yes. Make this visualization transparent by adding EditText android:textColorHighlight="@android:color/transparent" to the tag android:textColorHighlight="@android:color/transparent" - Flippy
 @Override protected void onSelectionChanged(int selStart, int selEnd) { setSelection(this.length()); } TextWatcher textWatcher = new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() > 0) { removeTextChangedListener(textWatcher); StringBuilder sb = new StringBuilder(s.toString()); setText(sb.deleteCharAt(0)); addTextChangedListener(textWatcher); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } };