searchEdit.addTextChangedListener(searchWatcher);//调用TextWatcher的方法
private TextWatcher searchWatcher = new TextWatcher() {//TextWatcher观察输入框中输入的内容
//在向输入框中输入之后
public void afterTextChanged(Editable arg0) {//arg0为输入框中的所有文字
System.out.println("--------00-------" + arg0);
}
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
System.out.println("charsequence----" + s + "--start---==" + start + "--count====" + count + "--after*****" + after);
// s:之前的文字内容 start:添加文字的位置 count:一直是0 after:此次添加的文字总数(并不是输入框中的文字的总数)
}public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {Log.d("TAG", "[TextWatcher][onTextChanged]" + s);System.out.println("onTextChanged" + "charsequence----" + s + "--start---==" + start + "--count====" + count);
//s:文本框中输入的所有文字 start:添加文字的位置 before:一直是0 count:此次添加文字的总个数
}
};
TextWatcher可以对EditText中输入的内容进行限制
<EditText android:id="@+id/ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
摘自: http://www.cnblogs.com/cat-fang/archive/2011/04/12/2013428.html
TextWatcher mTextWatcher = new TextWatcher() {
private CharSequence temp;
private int editStart ;
private int editEnd ;
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
temp = s;
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
mTextView.setText(s);
}
@Override
public void afterTextChanged(Editable s) {
editStart = mEditText.getSelectionStart();
editEnd = mEditText.getSelectionEnd();
if (temp.length() > 10) {
Toast.makeText(TextWatcherDemo.this,
"你输入的字数已经超过了限制!", Toast.LENGTH_SHORT)
.show();
s.delete(editStart-1, editEnd);
int tempSelection = editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
};