天天看点

EditText的InputFilter使用笔记

/**
 * InputFilters can be attached to {@link Editable}s to constrain the
 * changes that can be made to them.
 */
public interface InputFilter
{
    /**
     * This method is called when the buffer is going to replace the
     * range <code>dstart &hellip; dend</code> of <code>dest</code>
     * with the new text from the range <code>start &hellip; end</code>
     * of <code>source</code>.  Return the CharSequence that you would
     * like to have placed there instead, including an empty string
     * if appropriate, or <code>null</code> to accept the original
     * replacement.  Be careful to not to reject 0-length replacements,
     * as this is what happens when you delete text.  Also beware that
     * you should not attempt to make any changes to <code>dest</code>
     * from this method; you may only examine it for context.
     * 
     * Note: If <var>source</var> is an instance of {@link Spanned} or
     * {@link Spannable}, the span objects in the <var>source</var> should be 
     * copied into the filtered result (i.e. the non-null return value). 
     * {@link TextUtils#copySpansFrom} can be used for convenience.
     */
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend);

}
           

参数说明:

source:即将输入的文本

start:在输入的时候是0,删除的时候也是0

end:在输入的时候是source.length,在删除的时候是0

dest:在输入动作发生之前的文本

dstart:输入时,动作发生前的光标位置;删除时,光标删除的结束位置

dend:输入时,动作发生前的光标位置;删除时,光标删除的起始位置

return:是你希望添加的内容,如果返回""则不会添加任何内容,如果返回null就会将soure全部添加

最后需要注意的是在删除动作触发时,source的长度是0,这不是一个错误哦。另外不能直接修改dest的内容,否则会有神奇的事情发生。