本文主要是介绍android TextWatcher,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 ;@Overridepublic void beforeTextChanged(CharSequence s, int arg1, int arg2,int arg3) {temp = s;}@Overridepublic void onTextChanged(CharSequence s, int arg1, int arg2,int arg3) {mTextView.setText(s);}@Overridepublic 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);}}};
这篇关于android TextWatcher的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!