Reputation: 1139
I am working on custom edittext but i am little stuck in one thing, i found TextWatcher is not working in custom edittext.
public class InputValidation extends EditText {
public InputValidation(Context context) {
super(context);
}
public InputValidation(Context context, AttributeSet attrs) {
super(context, attrs);
}
public InputValidation(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void addTextChangedListener(android.text.TextWatcher watcher) {
super.addTextChangedListener(new TextWatcherDelegator());
}
public class TextWatcherDelegator implements android.text.TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
android.util.Log.d("TextWatcher", " beforeTextChanged :: " + charSequence.toString());
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(android.text.Editable editable) {
android.util.Log.d("TextWatcher", " afterTextChanged :: " + editable.toString());
}
}
}
XML layout
<com.example.inputvalidation.InputValidation
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="Fullname"
android:singleLine="true"
android:textSize="20sp"/>
Above this code it's not at all calling TextWatcher states, please kindly go through my code and suggest me some solution.
Upvotes: 0
Views: 1315
Reputation: 1167
Remove this, it's useless:
@Override
public void addTextChangedListener(android.text.TextWatcher watcher) {
super.addTextChangedListener(new TextWatcherDelegator());
}
Then, add/remove the TextWatcher
properly, for example in onAttachedToWindow
/onDetachedFromWindow
methods:
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
addTextChangedListener(textWatcher);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeTextChangedListener(textWatcher);
}
Also, textWatcher
should be an object, so it can be instanced from the TextWatcherDelegator
class:
TextWatcherDelegator textWatcher = new TextWatcherDelegator();
Or directly from TextWatcher
(which is better, if there's no other usages for TextWatcherDelegator
):
public TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
android.util.Log.d("TextWatcher", " beforeTextChanged :: " + charSequence.toString());
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(android.text.Editable editable) {
android.util.Log.d("TextWatcher", " afterTextChanged :: " + editable.toString());
}
}
Upvotes: 1