android api解析之TextWatcher

作者: lialzm | 来源:发表于2016-06-16 11:11 被阅读3214次

开发android有几年了,但是从来没有整理过,一直是写写写.从今天起开始慢慢整理,总结之处如有错误请指出,谢谢

TextWatcher在什么时候会被调用?
TextWatcher在edittext内容发生变化时会被调用
TextWatcher一共有三个方法
beforeTextChanged(CharSequence s, int start, int count, int after)
在文本变化前调用,start代表开始变化的位置,count代表变化的字符长度.after代表变化后字符该位置字符数量
onTextChanged(CharSequence s, int start, int before, int count)
在文本变化时调用,此时s的内容已发生改变,start代表开始变化的位置,before代表变化前该位置字符数量,count代表变化了的字符长度
afterTextChanged(Editable s)
在文本变化后调用,s即为变化后的文本结果
例子:
在空白输入框中输入一个字符

Paste_Image.png

第一条的意思是初始长度为0,变化的位置为0,变化的字符为0,变化后此位置为字符长度为1
第二条意思是此时字符长度为1,变化的位置为0,变化前字符长度为0,变化字符数量为1
第三条意思是变化结束后字符长度为1

下面是个小demo,实现了edittext信用卡格式,主要用到了TextWatcherEditable的一些方法

GIF.gif
public class CreditCardView extends EditText {
    public CreditCardView(Context context) {
        super(context);
        init();
    }

    public CreditCardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CreditCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        this.addTextChangedListener(setTextWatcher());
    }

    private TextWatcher setTextWatcher() {

        TextWatcher textWatcher = new TextWatcher() {
            //记录是否为删除
            boolean isDel = false;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.d("find", "beforeTextChangedlength=="+s.length() + ",start==" + start + ",count==" + count + ",after==" + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("find", "onTextChangedlength=="+s.length() + ",start==" + start + ",before==" + before + ",count==" + count);
                if (before > count) {//删除
                    isDel = true;
                } else {
                    isDel = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("find", "afterTextChangedlength=="+s.length());
                if (!isDel && s.length() > 0 &&s.length()>1&& (s.length()) % 5 == 0) {
                    //在指定位置之前插入
                    s.insert(s.length()-1,"-");
                }
                if (isDel && s.length() > 0&&s.length()>1 && (s.length()) % 5 == 0) {
                    //删除指定位置开区间[start,end)
                    s.delete(s.length() -1,s.length());
                }
            }
        };
        return textWatcher;
    }
}

相关文章

网友评论

    本文标题:android api解析之TextWatcher

    本文链接:https://www.haomeiwen.com/subject/ydemdttx.html