android textwatcher 获取当前控件,android api解析之TextWatcher

开发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即为变化后的文本结果

例子:

在空白输入框中输入一个字符

b77894408872

Paste_Image.png

第一条的意思是初始长度为0,变化的位置为0,变化的字符为0,变化后此位置为字符长度为1

第二条意思是此时字符长度为1,变化的位置为0,变化前字符长度为0,变化字符数量为1

第三条意思是变化结束后字符长度为1

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

b77894408872

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值