限制EditText 输入的字节数

1、代码   

 1         name_tv = (EditText) findViewById( R.id.name_tv );
 2         
 3         name_tv.addTextChangedListener(new TextWatcher() {
 4             @Override
 5             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 6             }
 7 
 8             @Override
 9             public void onTextChanged(CharSequence s, int start, int before, int count) {
10             }
11 
12             @Override
13             public void afterTextChanged(Editable s) {
14                 String string = s.toString().trim();
15 
16                 //限定输入框最多输入18个字节
17                 int inputLength = string.length();
18                 int byteLength = string.getBytes().length;
19                 if (byteLength >= 18) {
20                     name_tv.setFilters(new InputFilter[]{new InputFilter.LengthFilter(inputLength)});
21                 } else {
22                     name_tv.setFilters(new InputFilter[]{new InputFilter.LengthFilter(18)});
23                 }
24                 name_tv.setSelection(name_tv.getText().toString().length());
25             }
26         });

 

posted @ 2016-03-10 11:03  赵彦军  阅读(870)  评论(0编辑  收藏  举报