[html]
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中輸入的內容進行限制
[html]
<EditText android:id="@+id/ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
[html]
摘自: 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);
}
}
};