EditText过滤文本通过使用方法setFilters(InputFilter[] filters)完成。
/**
* 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 … dend</code> of <code>dest</code>
* with the new text from the range <code>start … 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 if the
* span boundary indices would be remaining identical relative to the source.
* @param source 用户键盘输入的文本
* @param start source的字符开始索引
* @param end source的字符结束索引(不包含)
* @param dest 目标替换文本
* @param dstart dest文本替换开始索引
* @param dend dest文本替换结束索引(添加文本时,dstart=dend)
* @return 返回实际输出到EditText的文本,空字符串则是不输出字符
*/
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend);
}
简单用法:
etMeetingTheme?.filters = arrayOf(object :InputFilter{
override fun filter(
source: CharSequence?,
start: Int,
end: Int,
dest: Spanned?,
dstart: Int,
dend: Int
): CharSequence {
logd("source=$source,start=$start,end=$end,dest=${dest},dstart=$dstart,dend=$dend")
return source.toString()
}
})
通过上述代码可以将输入原封不动输出到EditText并打印log。看下在各种场景下,打印的log
1.添加文本
已知条件:EditText暂无文本;
操作:键盘输入1
打印结果:
输出:1
已知条件:EditText已有文本ghhhhhhhhh
操作:键盘在文本g字符后输入5
打印结果:
输出:g5hhhhhhhhh
2.撤回文本
已知条件:EditText已有文本123456789;
操作:末尾撤回一格
打印:
输出:12345678
已知条件:EditText已有文本123456789;
操作:光标在4后,撤回一格
打印:
输出:12356789
已知条件:EditText已有文本123456789;
操作:选中234,并按下撤回
打印:
输出:156789
3.替换文本
已知条件:EditText已有文本123456789
操作:选中1234,并输入一二三四
打印:
输出:一二三四56789
例子:过滤特殊字符
class SpecialCharInputFilter:InputFilter {
override fun filter(
source: CharSequence?,
start: Int,
end: Int,
dest: Spanned?,
dstart: Int,
dend: Int
): CharSequence {
var sourceStr = source?.toString()
if(TextUtils.isEmpty(sourceStr))return ""
//过滤空格
var replace1 = sourceStr?.replace(" ", "")
//过滤特殊字符
val specialChars = arrayListOf<Char>()
replace1?.iterator()?.apply {
while (hasNext()){
val char = nextChar()
if(!char.isChinese() && !char.isLetterOrDigit() &&char !='-'){ //是特殊字符
specialChars.add(char)
}
}
}
specialChars.forEach {
replace1 = replace1?.replace(it.toString(), "")
}
return if(TextUtils.isEmpty(replace1))"" else replace1!!
}
}