Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android編程中EditText限制文字輸入的方法

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

編輯:關於Android編程

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

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

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

在Android裡使用TextWatcher接口可以很方便的對EditText進行監聽;TextWatcher中有3個函數需要重載:

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);

從函數名就可以知道其意思,每當敲擊鍵盤編輯框的文字改變時,上面的三個函數都會執行,beforeTextChanged可以給出變化之前的內容,onTextChanged和afterTextChanged給出追加上新的字符之後的文本;

所以對字符的限制判斷可以在afterTextChanged函數中進行,如果檢查到新追加的字符為認定的非法字符,則在這裡將其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();
   }
  }
 }
};

注冊監聽:

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

希望本文所述對大家Android程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved