为什么TextWatcher在android中的自定义Edittext中不起作用?

时间:2016-09-10 07:15:26

标签: android-edittext android-textwatcher

我正在开发自定义edittext,但我很少陷入困境,我发现TextWatcher无法使用自定义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布局

<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"/>

在此代码之上,它根本没有调用TextWatcher状态,请仔细阅读我的代码并建议我一些解决方案。

1 个答案:

答案 0 :(得分:0)

删除它,它没用:

@Override
public void addTextChangedListener(android.text.TextWatcher watcher) {
    super.addTextChangedListener(new TextWatcherDelegator());
}

然后,正确添加/删除TextWatcher,例如onAttachedToWindow / onDetachedFromWindow方法:

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    addTextChangedListener(textWatcher);
}

@Override
protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    removeTextChangedListener(textWatcher);
}

此外,textWatcher应该是一个对象,因此它可以来自TextWatcherDelegator类:

TextWatcherDelegator textWatcher = new TextWatcherDelegator();

或直接来自TextWatcher(如果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());
    }
}