您的位置:首页 > 其它

onTextChanged参数解释及实现EditText字数监听

2016-08-16 13:04 555 查看
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); 

        } 

    } 

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: