2017-03-21 2 views
0

私のアプリケーションのEditTextフィールドにいくつかの制約を加えようとしています。フルネームやその他のフィールドでは、文字、スペース、その他の文字を '。'または ' - '。TextChangedでのEditTextビューの検証

私はオンラインいくつかのものを見て、一緒にこれを置く:

mFullnameView = (EditText) findViewById(R.id.activity_register_et_fullname); 
TextWatcher fullnameTextWatcher = new TextWatcher() { 
    @Override 
    public void afterTextChanged(Editable s) { 
     validate(s.toString()); 
    } 

    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     // 
    } 

    private void validate(String s) { 
     if (!(Pattern.matches("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", s))) { 
      if (s.length() > 0) { 
       final String cleanText = s.substring(0, s.length()); 
       mFullnameView.setText(cleanText); 
      } 
     } 
    } 
}; 

を数秒間しかし今、私のアプリがフリーズし、その後、私はAを入力しようとするとクラッシュしました「」 EditTextフィールドに、なぜこれが起こるのか、それを解決する方法がわかりません。

+0

ユーザーがEditTextに入力できる内容を制限するだけで、検証を試みる必要はありません。このように:http://stackoverflow.com/a/23212485/2128028 – Everett

答えて

1

TextWatcherのテキストを変更すると、TextWatcherのメソッドが再度コールバックします。 したがって、再帰呼び出しを避けるか、InputFilterを使用する必要があります。

InputFilter[] filters = new InputFilter[1]; 
    filters[0] = new InputFilter() { 
     @Override 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
      if (source == null) return null; 
      Pattern p = Pattern.compile("^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$"); 
      Matcher m = p.matcher(source.toString()); 
      StringBuilder builder = new StringBuilder(); 
      while (m.find()) { 
       builder.append(m.group()); 
      } 
      return builder.toString(); 
     } 
    }; 
    mFullnameView.setFilters(filters); 
関連する問題