Android TextWatcher Example
In latest project, I need to implement an EditText to user enter facebook URL. I had two ideas for this.
[
Idea 1: A prefix added to EditText
and user can’t delete the prefix. They can just add more in EditText
to complete URL.
Idea 2: We have 2 components, the left is a TextView with value is http://www.facebook.com and the right is an EditText
.
What is better way?
I chooses case 1. And you?
In this tutorial I will give you an Android TextWatcher
example to illustrate the first idea.
TextWatcher
is used to keep watch on the Editable content while user input data. We can perform operation and keep watch on which characters are being entered or how to many characters are being entered in the EditText
.
TextWatcher
class has 3 methods and we need override these methods to implement functionality.
public abstract void afterTextChanged(Editable s)
This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively. (You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use [setSpan(Object, int, int, int)](http://developer.android.com/reference/android/text/Spannable.html#setSpan(java.lang.Object, int, int, int)) in [onTextChanged(CharSequence, int, int, int)](http://developer.android.com/reference/android/text/TextWatcher.html#onTextChanged(java.lang.CharSequence, int, int, int)) to mark your place and then look up from here where the span ended up.
public abstract void beforeTextChanged(CharSequence s, int start, int count, int after)
This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. It is an error to attempt to make changes to s from this callback.
public abstract void onTextChanged(CharSequence s, int start, int before, int count)
This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.
Now, I will show how to implement case 1 (use TextWatcher
):
Selection.setSelection(mEtFbFanpage.getText(), mEtFbFanpage.getText().length());
mEtFbFanpage.addTextChangedListener(new TextWatcher() {
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void afterTextChanged(Editable s) {
if (!s.toString().contains("https://facebook.com/")) {
mEtFbFanpage.setText("https://facebook.com/");
Selection.setSelection(mEtFbFanpage.getText(), mEtFbFanpage.getText().length());
}
}
});