Android TextWatcher三个回调以及监听EditText的输入案例详解

  // 用于屏蔽空格输入的TextWatcher

  TextWatcher watcher = new TextWatcher() {

  private String mBefore;// 用于记录变化前的文字

  private int mCursor;// 用于记录变化时光标的位置

  @Override

  public void beforeTextChanged(CharSequence s, int start, int count, int after) {

  mBefore = s.toString();

  mCursor = start;

  Log.d(TAG, "beforeTextChanged: " + s + ", " + mCursor);

  }

  @Override

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

  Log.d(TAG, "onTextChanged: " + s);

  }

  @Override

  public void afterTextChanged(Editable s) {

  Log.d(TAG, "afterTextChanged: " + s);

  // 这里图方便,是在afterTextChanged判断是否输入之后含有空格,并不是最好的方案

  // 理论上应该在onTextChanged中判断输入内容

  if (s.toString().contains(" ")) {

  Log.i(TAG, "onTextChanged: 包含空格, 设置" + mBefore);

  et.removeTextChangedListener(this);

  et.setText(mBefore);

  et.addTextChangedListener(this);

  et.setSelection(mCursor);

  }

  }

  };

  et.addTextChangedListener(watcher);