监听EditText实时输入

//要监听的EditText对象
private EditText mEditText;

//添加监听事件
mEditText.addTextChangedListener( new TextWatcher() {

  private CharSequence temp;
  private int start ;
  private int end ;

  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    temp = s;
  }

  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    
  }

  @Override
  public void afterTextChanged(Editable s) {
    start = mEditText.getSelectionStart();
    end = mEditText.getSelectionEnd();

    if (temp.length() > 5) {
      Toast.makeText(context, "input overflow", Toast.LENGTH_SHORT).show();
      s.delete(start-1, end);
      mEditText.setText(s);
      mEditText.setSelection(start);
    }
  }
});

//这样就可以限制输入内容在5个字符以内

 

posted @ 2014-05-25 22:54  x-dev  阅读(731)  评论(0编辑  收藏  举报