欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android EditText限制輸入字符類型的方法總結(jié)

 更新時(shí)間:2017年03月07日 15:13:21   投稿:lqh  
這篇文章主要介紹了Android EditText限制輸入字符類型的方法總結(jié)的相關(guān)資料,需要的朋友可以參考下

Android EditText限制輸入字符類型的方法總結(jié)

前言:

最近的項(xiàng)目上需要限制EditText輸入字符的類型,就把可以實(shí)現(xiàn)這個(gè)功能的方法整理了一下:

1、第一種方式是通過(guò)EditText的inputType來(lái)實(shí)現(xiàn),可以通過(guò)xml或者Java文件來(lái)設(shè)置。假如我要設(shè)置為顯示密碼的形式,可以像下面這樣設(shè)置:

在xml中

 Android:inputType="textPassword"

在java文件中,可以用 myEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
當(dāng)然,還有更多的其他屬性用來(lái)進(jìn)行輸入設(shè)置。

2、第二種是通過(guò)android:digits 屬性來(lái)設(shè)置,這種方式可以指出要顯示的字符,比如我要限制只顯示數(shù)字,可以這樣:

   android:digits="0123456789"

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

3、通過(guò)正則表達(dá)式來(lái)判斷。下面的例子只允許顯示字母、數(shù)字和漢字。

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

然后需要在TextWatcher的onTextChanged()中調(diào)用這個(gè)函數(shù),

@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);
       //設(shè)置新的光標(biāo)所在位置 
       editText.setSelection(str.length());
     }
   } 

4、通過(guò)InputFilter來(lái)實(shí)現(xiàn)。

實(shí)現(xiàn)InputFilter過(guò)濾器,需要覆蓋一個(gè)叫filter的方法。

public abstract CharSequence filter ( 
  CharSequence source, //輸入的文字 
  int start, //開始位置 
  int end, //結(jié)束位置 
  Spanned dest, //當(dāng)前顯示的內(nèi)容 
  int dstart, //當(dāng)前開始位置 
  int dend //當(dāng)前結(jié)束位置 
);

下面的實(shí)現(xiàn)使得EditText只接收字符(數(shù)字、字母和漢字)和“-”“_”,Character.isLetterOrDigit會(huì)把中文也當(dāng)做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還能限制輸入的字符個(gè)數(shù),如   

  EditText tv =newEditText(this); 

    int maxLength =10; 

    InputFilter[] fArray =new InputFilter[1]; 

    fArray[0]=new InputFilter.LengthFilter(maxLength); 

    tv.setFilters(fArray);

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

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論