TextView和EditText中的setFilters方法说明

        在TextView中有一个方法public void setFilters(InputFilter[] filters),API中有一句说明:Sets the list of input filters that will be used if the buffer is Editable.  Has no effect otherwise。InputFilter的作用是对输入的文字进行过滤,可以自定义处理,这句话的意思是可以设置自定义处理对象列表,但是他们是否会起作用还要看TextView的文字缓冲区是否是Editable。

       所以,我们进到Editable的API页面,可以看到Editable类也有个方法public void setFilters(InputFilter[] filters),翻开TextView源码可以看到下面两段代码:

public void setFilters(InputFilter[] filters) {
        if (filters == null) {
            throw new IllegalArgumentException();
        }

        mFilters = filters;

        if (mText instanceof Editable) {
            setFilters((Editable) mText, filters);
        }
}

private void setFilters(Editable e, InputFilter[] filters) {
        if (mEditor != null && mEditor.mKeyListener instanceof InputFilter) {
            InputFilter[] nf = new InputFilter[filters.length + 1];

            System.arraycopy(filters, 0, nf, 0, filters.length);
            nf[filters.length] = (InputFilter) mEditor.mKeyListener;

        } else {
            e.setFilters(filters);
        }
}
        通过上面的代码可以看到,TextView的 setFilters方法实际上是Editable对象setFilters方法的代理。在Editable类API中对setFilters方法的描述是这样的:Sets the series of filters that will be called in succession whenever the text of this Editable is changed, each of which has the opportunity to limit or transform the text that is being inserted。意思大概是说,这个方法为Editable对象设置了一组文字过滤器,当文字发生变化时,每一个过滤器都有机会发生作用。

        Android SDK中定义了一组InputFilter接口的实现,但是,大多数时间我们可以自己实现InputFilter接口,主要是实现CharSequence filter(CharSequence source,int start,int end,Spanned dest,int dstart,int dend)接口方法,这里六个参数的意义分别为:

source新输入的字符串
start新输入的字符串起始下标,一般为0
end新输入的字符串终点下标,一般为source长度-1
dest输入之前文本框内容
dstart原内容起始坐标,一般为0
dend原内容终点坐标,一般为dest长度-1
        我们可以在filter实现方法中对source进行判断处理,并返回一个CharSequence对象,追加到dest后面;

        这里给出一个示例程序的链接,大家可以去试验一下>>点这里,点这里。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值