如何在android中自定义Edittext中设置过滤器?

时间:2016-09-09 09:13:53

标签: android android-edittext

我正在制作自定义edittext,我想设置过滤器,但我不知道如何实现。

public class CharacterEdittext extends EditText {

   public static final String blockCharacterSet = "~#^|$%&*!`.%$-+()@/*1234567890_\":;?={}[]\\%<>£™¢∞§¶•ªº–≠œ∑´†¥¨ˆπ“‘«å∂ƒ©˙∆˚¬…æΩç√∫˜µ≤≥µ,÷≠`«'°®⨯€c/o";

public CharacterEdittext(android.content.Context context) {
    super(context);
}

public CharacterEdittext(android.content.Context context, android.util.AttributeSet attrs) {
    super(context, attrs);
}

public CharacterEdittext(android.content.Context context, android.util.AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public static android.text.InputFilter characterfilter = new android.text.InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, android.text.Spanned dest, int dstart, int dend) {

        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

  @Override
  public void setFilters(android.text.InputFilter[] filters) {
    super.setFilters(filters);
  }
}

请仔细阅读我的代码,并向我提出一些解决方案。

1 个答案:

答案 0 :(得分:0)

将代码放在构造函数中。

InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        boolean keepOriginal = true;
        StringBuilder sb = new StringBuilder(end - start);
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (isCharAllowed(c)) // put your condition here
                sb.append(c);
            else
                keepOriginal = false;
        }
        if (keepOriginal)
            return null;
        else {
            if (source instanceof Spanned) {
                SpannableString sp = new SpannableString(sb);
                TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                return sp;
            } else {
                return sb;
            }           
        }
    }

    private boolean isCharAllowed(char c) {
        return blockCharacterSet.indexOf(c) >= 0;
    }
}
setFilters(new InputFilter[] { filter });