请有人向我解释android.text.InputFilter#filter
中源参数和dest参数的用途?
我试着看了一下文件,但我真的很困惑。我正在尝试使用正则表达式来制作IP掩码。感谢您的帮助。
我现在明白了。因此,例如,如果我有123.42,那么用户键入123.42d,我将有:
dest = 123.42
source = 123.42d
start = 5
end = 6
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter()
{
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
{
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
if(resultingTxt.equals("")) return "";
int lastChar = resultingTxt.length() -1;
if(String.valueOf(resultingTxt.charAt(lastChar)).matches("[^0-9.]"))
{
return "";
}
return null;
}
};
但这不起作用。这不应该只给我数字吗?碰巧的是,根据用户的类型,它也会向我返回字符。
如果您有一个EditText
并为其分配了一个InputFilter
,那么每次更改其中的文本时,都会调用filter()
方法。很像按钮的onClick()
方法。
假设您在编辑EditText之前已经在其中输入了文本"Hello Androi"虚拟键盘上的D
键,则会触发inputfilter,并基本上询问是否可以添加d
。
在这种情况下,source
是"Android",开始是6,结束是7——这是你对新文本的引用。
dest
将是"Androi",指的是EditText
中的旧文本
所以你得到了新的字符串和字符串中的一个位置(6,7),你必须检查它是否正常。如果你只得到一个字符(比如d
),你就无法决定你刚刚输入的数字是否构成ip地址。在某些情况下,您需要将整个文本作为上下文。
如果新文本可以原样返回null
,如果要跳过更改,则返回空字符串(""
),否则返回替换更改的字符。
因此,一个简单的例子可能是:
/**
* Simplified filter that should make everything uppercase
* it's a demo and will probably not work
* - based on InputFilter.AllCaps
*/
public static class AllCaps implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// create a buffer to store the edited character(s).
char[] v = new char[end - start];
// extract the characters between start and end into our buffer
TextUtils.getChars(source, start, end, v, 0);
// make the characters uppercase
String s = new String(v).toUpperCase();
// and return them
return s;
}
}
它用大写版本替换每一个更改。