Android---3种方式限制EditView输入字数(转载)

 方法一:利用TextWatcher

Java代码  收藏代码
  1. editText.addTextChangedListener(new TextWatcher() {  
  2.            private CharSequence temp;  
  3.            private boolean isEdit = true;  
  4.            private int selectionStart ;  
  5.            private int selectionEnd ;  
  6.            @Override  
  7.            public void beforeTextChanged(CharSequence s, int arg1, int arg2,  
  8.                    int arg3) {  
  9.                temp = s;  
  10.            }  
  11.              
  12.            @Override  
  13.            public void onTextChanged(CharSequence s, int arg1, int arg2,  
  14.                    int arg3) {  
  15.            }  
  16.              
  17.            @Override  
  18.            public void afterTextChanged(Editable s) {  
  19.                 selectionStart = editText.getSelectionStart();  
  20.                selectionEnd = editText.getSelectionEnd();  
  21.                Log.i("gongbiao1",""+selectionStart);  
  22.                if (temp.length() > Constant.TEXT_MAX) {  
  23.                    Toast.makeText(KaguHomeActivity.this,  
  24.                            R.string.edit_content_limit, Toast.LENGTH_SHORT)  
  25.                            .show();  
  26.                    s.delete(selectionStart-1, selectionEnd);  
  27.                    int tempSelection = selectionStart;  
  28.                    editText.setText(s);  
  29.                    editText.setSelection(tempSelection);  
  30.                }  
  31.            }  
  32.   
  33.   
  34.        });  

方法二:利用InputFilter

    

Java代码  收藏代码
  1. editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});  //其中100最大输入字数  

方法三:在XML中设定

Xml代码  收藏代码
  1. <EditText  
  2.     .  
  3.     .  
  4.     .  
  5.     android:maxLength="100"  
  6. />  
原文地址:https://www.cnblogs.com/xiaochao1234/p/4112253.html