您的位置:首页 > 移动开发 > Android开发

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

2016-12-20 09:52 561 查看
//转自  http://blog.csdn.net/studynote/article/details/37928399


一: 声明控件。
         TextView hasnumTV;
        TextView hasnum;// 用来显示剩余字数
        int num = 50;// 限制的最大字数
二: 主要的方法:
[java] view plain copy print?hasnumTV = (TextView) findViewById(R.id.tv_num);  
  
              hasnumTV.setText("限" + num + "" + "字以内");  
  
              editText.addTextChangedListener(new TextWatcher() {  
  
                      private CharSequence temp;  
  
                      private int selectionStart;  
  
                      private int selectionEnd;  
  
                      @Override  
  
                      public void onTextChanged(CharSequence s, int start, int before,  
  
                                      int count) {  
  
                      }  
  
                      public void beforeTextChanged(CharSequence s, int start, int count,  
  
                                      int after) {  
  
                              temp = s;  
  
                      }  
  
                      public void afterTextChanged(Editable s) {  
  
                              // TODO Auto-generated method stub  
  
                              int number = num - s.length();  
  
                              hasnumTV.setText("剩余" + "" + number + "个字");  
  
                              selectionStart = editText.getSelectionStart();  
  
                              selectionEnd = editText.getSelectionEnd();  
  
                              if (temp.length() > num) {  
  
                                      s.delete(selectionStart - 1, selectionEnd);  
  
                                      int tempSelection = selectionEnd;  
  
                                      editText.setText(s);  
  
                                      editText.setSelection(tempSelection);// 设置光标在最后  
  
                              }  
  
                      }  
  
              });  



主要的效果是做到了输入的限制文字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: