三种方式去限制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. /> 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值