I need to do an EditText that will only accept one character and only a character (letter / alpha). And if the user enters another char, he must replace the existing one (for example, a method of rewriting text input with 1 valid character).
I know how to set the maximum length of text in properties. But if I set it to 1, then no other char can be inserted before the user removes the existing one. But I want to replace the existing char with the newly entered one automatically without manual deletion. How to do it?
I know how to set a property to allow only numbers in an EditText , but I cannot figure out how to allow only characters. So the second question is how to allow only characters in an EditText ?
I am currently using EditText with maximum text size = 2 with the following code:
final EditText editLetter = (EditText)findViewById(R.id.editHouseLetter); editLetter.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { if (s!=null && s.length()>1){ editLetter.setText(s.subSequence(1, s.length())); editLetter.setSelection(1); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } });
The fact is that when the user enters the second char, the first must be deleted. If the text size is 2, the user can enter another char after it has already been entered.
I really don't understand how this works, but it does :). And in addition, I had to move the cursor over EditText to the last position, because it always goes to the beginning, which makes it impossible to enter anything. It didn’t work out why this is either.
The main point of this solution is that it has a size of 2 tars EditText , but I want it 1 char. And it allows you to enter anything except letters (characters / alpha), and I want nothing but characters.
Using the recommendations of sgarman and Character.isLetter() , the afterTextChanged method looks like this:
public void afterTextChanged(Editable s) { int iLen=s.length(); if (iLen>0 && !Character.isLetter((s.charAt(iLen-1)))){ s.delete(iLen-1, iLen); return; } if (iLen>1){ s.delete(0, 1); } }
I found that using Selection.setSelection is not required in this case. Now he has a filter that allows you to enter only letters. This is almost the answer I want. Only one thing remains: to do the same with the 1-character size of the EditText ?