前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android textwatcher 获取当前控件,android api解析之TextWatcher

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

作者头像
全栈程序员站长
发布2022-07-23 13:26:34
5000
发布2022-07-23 13:26:34
举报
文章被收录于专栏:全栈程序员必看

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

开发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信用卡格式,主要用到了TextWatcher和Editable的一些方法

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;

}

}

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月7,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档