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

开发android有几年了,但是从来没有整理过,一直是写写写.从今天起开始慢慢整理,总结之处如有错误请指出,谢谢TextWatcher在什么时候会被调用?TextWatcher在edittext内容发生变化时会被调用TextWatcher一共有三个方法beforeTextChanged(CharSequences,intstart,intcount,intafter)在文本变化前调用…

大家好,又见面了,我是你们的朋友全栈君。

开发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;

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/126485.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号