首页 > 解决方案 > Edittext 移除 textchangedlistener

问题描述

我一直在寻找有关如何删除文本更改侦听器的答案。

这是我当前的代码:

 public void enableTextChangedListener(boolean enableFormatting){
        if (enableFormatting) {
            if (!"1".equals(mAmountEditText.getTag())) {
                mAmountEditText.addTextChangedListener(new StringUtils.NumberTextWatcherForThousand(mAmountEditText));
                mAmountEditText.setTag("1");

  }
        }
        else {
            mAmountEditText.removeTextChangedListener(new StringUtils.NumberTextWatcherForThousand(mAmountEditText));
        }
    }

当我的布尔 enableFormatting 为 False 时,textchangelistener 仍然存在。

如果您想更清楚地解释我的代码,我可以提供 NumberTextwatcherForThousands 类。

标签: androidandroid-edittextaddtextchangedlistener

解决方案


您需要保留对侦听器的引用,现在您在尝试删除旧侦听器时正在创建一个新侦听器。像这样的东西:

textWatcher = new StringUtils.NumberTextWatcherForThousand(mAmountEditText);
public void enableTextChangedListener(boolean enableFormatting){
    if (enableFormatting) {
        if (!"1".equals(mAmountEditText.getTag())) {
            mAmountEditText.addTextChangedListener(textWatcher);
            mAmountEditText.setTag("1");

}
    }
    else {
        mAmountEditText.removeTextChangedListener(textWatcher);
    }
}

推荐阅读