android - Android 仅字母数字,以编程方式(非 XML)
问题描述
我在 Android 中有一个程序,其中一个 AutoCompleteTextView 名为aCTVNumeroPoste。
此 AutoCompleteTextView 更改输入类型取决于其他选项。
所以选项 1 使 AutoCompleteTextView 仅Text和选项 2 使 AutoCompleteTextView 仅Numbers。这似乎适用于键盘。
但是问题是当 AutoCompleteTextView 是文本时,我只想要字母数字,键盘允许我引入$%&/()=?¡"!-.等。
继承人的代码:
if (accion.equals("MANTENIMIENTO")) {
aCTVNumeroPoste.setInputType(InputType.TYPE_CLASS_TEXT);
int maxLengthofEditText = 19;
aCTVNumeroPoste.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});
}
else {
aCTVNumeroPoste.setInputType(InputType.TYPE_CLASS_NUMBER);
aCTVNumeroPoste.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
int maxLengthofEditText = 3;
aCTVNumeroPoste.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});
}
我想以编程方式解决这个问题,而不是在 XML 中(使用 android:digits=...)。
在InputType.TYPE_CLASS_TEXT之后,我尝试使用此代码:
aCTVNumeroPoste.setFilters(new InputFilter[]{
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if (src.equals("")) {
return src;
}
if (src.toString().matches("[a-zA-Z 0-9]+")) {
return src;
}
return "";
}
}
});
还有这个:
aCTVNumeroPoste.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "));
但没有任何效果。任何帮助表示赞赏。
解决方案
我回答我自己的问题。
这段代码对我有用:
public static class AlphaNumericInputFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// Only keep characters that are alphanumeric
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (Character.isLetterOrDigit(c)) {
builder.append(c);
}
}
// If all characters are valid, return null, otherwise only return the filtered characters
boolean allCharactersValid = (builder.length() == end - start);
return allCharactersValid ? null : builder.toString();
}
}
然后在InputType.TYPE_CLASS_TEXT之后添加:
// Apply the filters to control the input (alphanumeric)
ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(aCTVNumeroPoste.getFilters()));
curInputFilters.add(0, new AlphaNumericInputFilter());
curInputFilters.add(1, new InputFilter.LengthFilter(maxLengthofEditText));
InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
aCTVNumeroPoste.setFilters(newInputFilters);
推荐阅读
- rust - 如何在 Substrate 中实现后台线程?
- macos - 运行 sudo gcloud...(macOS Catalina)后,主目录中的权限被拒绝
- micropython - 如何在电机和传感器之间获得即时响应?
- javascript - 在 Next.js 中获取非 API 数据的最佳实践是什么(通过 Vercel 部署)
- google-sheets - 谷歌表格。是否可以给一个词一个值?
- python-3.x - 如何在django中指定http请求的类型
- css - 将 css 线性渐变转换为 react-native-linear-gradient
- node.js - Aws ecs 任务 IP 地址在 nodejs 一段时间后停止工作
- javascript - Storybook 在preview-head.html 中的所有链接和脚本的http: 之后添加一个句点,如何删除它
- python - 如何在虚拟环境中调用python函数?