Android中EditText的监听接口,TextWatcher。
它有三个成员方法,第一个after很简单,这个方法就是在EditText内容已经改变之后调用,重点看下面两个方法:
beforeTextChanged(CharSequence s, int start, int count, int after)
这个方法是在Text改变之前被调用,它的意思就是说在原有的文本s中,从start开始的count个字符将会被一个新的长度为after的文本替换,注意这里是将被替换,还没有被替换。
onTextChanged(CharSequence s, int start, int before, int count)
这个方法是在Text改变过程中触发调用的,它的意思就是说在原有的文本s中,从start开始的count个字符替换长度为before的旧文本,注意这里没有将要之类的字眼,也就是说一句执行了替换动作。
那么我们如何利用这个接口监听EditText的文本变化来实现限制输入字数的功能呢,我相信大家都有自己的想法了,这里我给出自己的一个简单实现,主要代码如下:
source_des.addTextChangedListener(new TextWatcher() {
private static final String TAG = "main"; private CharSequence temp; private int selectionStart; private int selectionEnd; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d(TAG, "onTextChanged 被执行---->s=" + s + "----start="+ start + "----before="+before + "----count" +count); temp = s; } public void beforeTextChanged(CharSequence s, int start, int count,int after) { Log.d(TAG, "beforeTextChanged 被执行----> s=" + s+"----start="+ start + "----after="+after + "----count" +count); }
public void afterTextChanged(Editable s) { Log.d(TAG, "afterTextChanged 被执行---->" + s); selectionStart = source_des.getSelectionStart(); selectionEnd = source_des.getSelectionEnd(); if (temp.length() > MAX_LENGTH) { Toast.makeText(MainActivity.this, "只能输入九个字", Toast.LENGTH_SHORT).show(); s.delete(selectionStart - 1, selectionEnd); int tempSelection = selectionEnd; source_des.setText(s); source_des.setSelection(tempSelection); } } });
