There is an EditText in which the user enters numbers, it is necessary to prohibit to enter a zero, at that 10, 100, 1000, ... can be entered. How to correctly register inputFilter in this case?
|
2 answers
As far as I know, this can be done only with the help of Java manipulations. For example:
editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if("0".equals(editText.getText())) { editText.setText(""); } } @Override public void afterTextChanged(Editable s) { } }); - And what will happen if you dial 12340? :) - mit
- one@mit I began to doubt, so I changed the answer. So sure it will be right - Vladyslav Matviienko
- For comparison, in
equals()isn't it necessary to result in aString-editText.getText().toString()? - pavlofff - @pavlofff, I'm not sure, maybe it should - Vladyslav Matviienko
|
editText.addTextChangedListener(new TextWatcher(){ public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().matches("^0") ) { editText.setText(""); editText.setError("Zero is not valid input"); } } @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} }); We check the input with a regular expression - if 0 is at the beginning, then we reset the input and display a warning about the input error so that the user does not break the screen :)
Behind this code, more flexible adaptation if more complex validation is required (regular expression can be very complex)
|
EditTextattribute inputType = "number", convert the input to a number and compare with 0? - pavlofff