限制EditText输入文字的数目

1、在xml布局中设置

android:maxLength="36"

2、通过代码设置

editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(36)}); 

3、通过设置editText的监听

private TextWatcher mTextWatcher = new TextWatcher(){
  Toast mToast = null;
  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) {
   int nSelStart = 0;
   int nSelEnd = 0;
   boolean nOverMaxLength = false;
   
   nSelStart = mEditText.getSelectionStart();
   nSelEnd   = mEditText.getSelectionEnd();
   
   nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false;
   if(nOverMaxLength){
    if(null == mToast){
     mToast = Toast.makeText(mContext, 
       R.string.IDS_MSG_TEXT_OVER_MAXLENGTH, 
       Toast.LENGTH_SHORT);
    }
    mToast.show();
    
    s.delete(nSelStart - 1, nSelEnd);
    mEditText.setTextKeepState(s);//请读者注意这一行,保持光标原先的位置,而 mEditText.setText(s)会让光标跑到最前面,
                                                     //就算是再加mEditText.setSelection(nSelStart) 也不起作用
    }
  }
 };


你可能感兴趣的:(android,EditText)