亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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

在Android里使用TextWatcher接口可以很方便的對EditText進行監(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ù)名就可以知道其意思,每當敲擊鍵盤編輯框的文字改變時,上面的三個函數(shù)都會執(zhí)行,beforeTextChanged可以給出變化之前的內容,onTextChanged和afterTextChanged給出追加上新的字符之后的文本;

所以對字符的限制判斷可以在afterTextChanged函數(shù)中進行,如果檢查到新追加的字符為認定的非法字符,則在這里將其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程序設計有所幫助。

相關文章

最新評論