Android 禁止EditText 输入 空格和特殊字符

2021-02-23  本文已影响0人  会Android的摄影爱好者
/**
  * 禁止EditText输入空格
  * @param editText
  */
 public static void setEditTextInhibitInputSpace(EditText editText){
  InputFilter filter=new InputFilter() {
   @Override
   public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    if(source.equals(" ")return "";
    else return null;
   }
  };
  editText.setFilters(new InputFilter[]{filter});
 }

/**
  * 禁止EditText输入特殊字符
  * @param editText
  */
 public static void setEditTextInhibitInputSpeChat(EditText editText){
  InputFilter filter=new InputFilter() {
   @Override
   public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    String speChat="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“'。,、?]";
    Pattern pattern = Pattern.compile(speChat);
    Matcher matcher = pattern.matcher(source.toString());
    if(matcher.find())return "";
    else return null;
   }
  };
  editText.setFilters(new InputFilter[]{filter});
 }
上一篇下一篇

猜你喜欢

热点阅读