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

Android編程中EditText限制文字輸入的方法

 更新時間:2015年11月04日 14:52:20   作者:Just run  
這篇文章主要介紹了Android編程中EditText限制文字輸入的方法,涉及Android針對EditText的監(jiān)聽技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了Android編程中EditText限制文字輸入的方法。分享給大家供大家參考,具體如下:

Android的編輯框控件EditText在平常編程時會經(jīng)常用到,有時候會對編輯框增加某些限制,如限制只能輸入數(shù)字,最大輸入的文字個數(shù),不能輸入一些非法字符等,這些需求有些可以使用android控件屬性直接寫在布局xml文件里,比如android:numeric="integer"(只允許輸入數(shù)字);

對于一些需求,如非法字符限制(例如不允許輸入#號,如果輸入了#給出錯誤提示),做成動態(tài)判斷更方便一些,而且容易擴(kuò)展;

在Android里使用TextWatcher接口可以很方便的對EditText進(jìn)行監(jiān)聽;TextWatcher中有3個函數(shù)需要重載:

public void beforeTextChanged(CharSequence s, int start, int count, int after);
public void onTextChanged(CharSequence s, int start, int before, int count);
public void afterTextChanged(Editable s);

從函數(shù)名就可以知道其意思,每當(dāng)敲擊鍵盤編輯框的文字改變時,上面的三個函數(shù)都會執(zhí)行,beforeTextChanged可以給出變化之前的內(nèi)容,onTextChanged和afterTextChanged給出追加上新的字符之后的文本;

所以對字符的限制判斷可以在afterTextChanged函數(shù)中進(jìn)行,如果檢查到新追加的字符為認(rèn)定的非法字符,則在這里將其delete掉,那么他就不會顯示在編輯框里了:

private final TextWatcher mTextWatcher = new TextWatcher() {
 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 } 
 public void onTextChanged(CharSequence s, int start, int before, int count) {
 } 
 public void afterTextChanged(Editable s) {
  if (s.length() > 0) {
   int pos = s.length() - 1;
   char c = s.charAt(pos);
   if (c == '#') {
   //這里限制在字串最后追加#
    s.delete(pos,pos+1);
    Toast.makeText(MyActivity.this, "Error letter.",Toast.LENGTH_SHORT).show();
   }
  }
 }
};

注冊監(jiān)聽:

EditText mEditor = (EditText)findViewById(R.id.editor_input);
mEditor.addTextChangedListener(mTextWatcher);

希望本文所述對大家Android程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論