0

我正在处理自定义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 状态,请仔细阅读我的代码并建议我一些解决方案。

4

1 回答 1

1

去掉这个,没用:

@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());
    }
}
于 2018-04-27T15:12:43.050 回答