EditText限制輸入字符類型的幾種方式


   最近的項目上需要限制EditText輸入字符的類型,就把可以實現這個功能的方法整理了一下:

1、第一種方式是通過EditText的inputType來實現,可以通過xml或者Java文件來設置。假如我要設置為顯示密碼的形式,可以像下面這樣設置:

在xml中,   Android:inputType="textPassword"

在java文件中,可以用 myEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

當然,還有更多的其他屬性用來進行輸入設置。

 

2、第二種是通過android:digits 屬性來設置,這種方式可以指出要顯示的字符,比如我要限制只顯示數字,可以這樣:

        android:digits="0123456789"

如果要顯示的內容比較多,就比較麻煩了,將要顯示的內容依次寫在里面。


3、通過正則表達式來判斷。下面的例子只允許顯示字母、數字和漢字。

public static String stringFilter(String str)throws PatternSyntaxException{     
      // 只允許字母、數字和漢字      
      String   regEx  =  "[^a-zA-Z0-9\u4E00-\u9FA5]";                     
      Pattern   p   =   Pattern.compile(regEx);     
      Matcher   m   =   p.matcher(str);     
      return   m.replaceAll("").trim();     
  }

然后需要在TextWatcher的onTextChanged()中調用這個函數,

@Override  
      public void onTextChanged(CharSequence ss, int start, int before, int count) {  
          String editable = editText.getText().toString();  
          String str = stringFilter(editable.toString());
          if(!editable.equals(str)){
              editText.setText(str);
              //設置新的光標所在位置  
              editText.setSelection(str.length());
          }
      }  

 

4、通過InputFilter來實現。

 

實現InputFilter過濾器,需要覆蓋一個叫filter的方法。

public abstract CharSequence filter ( 

    CharSequence source,  //輸入的文字 

    int start,  //開始位置 

    int end,  //結束位置 

    Spanned dest, //當前顯示的內容 

    int dstart,  //當前開始位置 

    int dend //當前結束位置 

);

下面的實現使得EditText只接收字符(數字、字母和漢字)和“-”“_”,Character.isLetterOrDigit會把中文也當做Letter。

editText.setFilters(new InputFilter[] { 

new InputFilter() { 
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
            for (int i = start; i < end; i++) { 
                    if ( !Character.isLetterOrDigit(source.charAt(i)) && !Character.toString(source.charAt(i)) .equals("_") && !Character.toString(source.charAt(i)) .equals("-")) { 
                            return ""; 
                    } 
            } 
            return null; 

    }  }); 

 

另外使用InputFilter還能限制輸入的字符個數,如

        EditText tv =newEditText(this); 
        int maxLength =10; 
        InputFilter[] fArray =new InputFilter[1]; 
        fArray[0]=new  InputFilter.LengthFilter(maxLength); 
        tv.setFilters(fArray);

上面的代碼可以限制輸入的字符數最大為10。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM