I have a form where the user can enter some data in EditText fields. One of those EditText widgets is for the email address. I am using a TextWatcher to make sure that the text is always lowercase as follows:
txtEmail.addTextChangedListener(new TextWatcher()
{
String prevString = "";
boolean delAction = false;
@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 (s.length() < prevString.length())
delAction = true;
else
delAction = false;
}
@Override
public void afterTextChanged(Editable s)
{
if (!delAction)
{
String temp = s.toString().toLowerCase();
if (!temp.equals(prevString))
{
prevString = temp;
txtEmail.setText(temp); // Recursive
txtEmail.setSelection(temp.length());
}
}
else
{
prevString = s.toString();
}
}
});
In the onTextChanged(...)
I am also making a comparison to make sure that deleting works properly.
Now to the problem. txtEmail.setText(temp);
is causing the whole Watcher to run recursively. I can control the caret position to go to the end of the EditText by adding txtEmail.setSelection(temp.length());
and escape the recursive loop with the if
but I cannot find a way to keep my caret at a specific point. If for example I wrote "myema(il missing)@something.com and want to go back to make my correction at each letter typed the caret goes at the end of the string.
Now the weird part. I tried keeping the position of the caret before the beforeTextChanged(...)
or in onTextChanged(...)
. The moment I type something the caret position is properly changed in every case. The moment, though, we enter the recursive call the position of the caret is reported as 0. I am guessing that when I actually type, the caret movement is also registered but because in the recursive call there is no caret movement rather than "pasting" of text in the EditText I get no position change.
And thus the question: How can I keep the position of the caret? The thought I had was to actually sub string the text. Get everything to the caret make the changes throw it there with the txtEmail.setSelection(temp.length());
and then append the rest of the string in the else step (not tried as of yet). Is there any other (simpler/efficient) way I could handle that with inbuilt tools?
Thanks in advance!