转 Android实现限制EditText输入文字的数量

来源:互联网 发布:苹果cms资源采集插件 编辑:程序博客网 时间:2024/05/23 15:46
//转自  http://blog.csdn.net/studynote/article/details/37928399 

一: 声明控件。

         TextView hasnumTV;

        TextView hasnum;// 用来显示剩余字数

        int num = 50;// 限制的最大字数

二: 主要的方法:

[java] view plain copy print?
  1. hasnumTV = (TextView) findViewById(R.id.tv_num);  
  2.   
  3.               hasnumTV.setText("限" + num + "" + "字以内");  
  4.   
  5.               editText.addTextChangedListener(new TextWatcher() {  
  6.   
  7.                       private CharSequence temp;  
  8.   
  9.                       private int selectionStart;  
  10.   
  11.                       private int selectionEnd;  
  12.   
  13.                       @Override  
  14.   
  15.                       public void onTextChanged(CharSequence s, int start, int before,  
  16.   
  17.                                       int count) {  
  18.   
  19.                       }  
  20.   
  21.                       public void beforeTextChanged(CharSequence s, int start, int count,  
  22.   
  23.                                       int after) {  
  24.   
  25.                               temp = s;  
  26.   
  27.                       }  
  28.   
  29.                       public void afterTextChanged(Editable s) {  
  30.   
  31.                               // TODO Auto-generated method stub  
  32.   
  33.                               int number = num - s.length();  
  34.   
  35.                               hasnumTV.setText("剩余" + "" + number + "个字");  
  36.   
  37.                               selectionStart = editText.getSelectionStart();  
  38.   
  39.                               selectionEnd = editText.getSelectionEnd();  
  40.   
  41.                               if (temp.length() > num) {  
  42.   
  43.                                       s.delete(selectionStart - 1, selectionEnd);  
  44.   
  45.                                       int tempSelection = selectionEnd;  
  46.   
  47.                                       editText.setText(s);  
  48.   
  49.                                       editText.setSelection(tempSelection);// 设置光标在最后  
  50.   
  51.                               }  
  52.   
  53.                       }  
  54.   
  55.               });  
主要的效果是做到了输入的限制文字
0 0
原创粉丝点击