I have an input on my android app, the text from this input is sent to my server and then later retrieved by another front end to be displayed. the other front end can only work with ISO-8859-1 character set and will crash if any other characters are encountered(its an old software) so I need to restrict the EditText to only allow ISO-8859-1 characters and I'm not sure how I can achieve this.
[EDIT]
So big thanks to aarnaut for the help, this is what I have ended up with:
public class ISO_8859_1_InputFilter implements InputFilter {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharsetEncoder iso_8859_1 = Charset.forName("ISO_8859_1").newEncoder();
if (source instanceof SpannableStringBuilder) {
SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
for (int i = end - 1; i >= start; i--) {
char currentChar = source.charAt(i);
if (!iso_8859_1.canEncode(currentChar)) {
sourceAsSpannableBuilder.delete(i, i + 1);
}
}
return source;
} else {
StringBuilder filteredStringBuilder = new StringBuilder();
for (int i = start; i < end; i++) {
char currentChar = source.charAt(i);
if (iso_8859_1.canEncode(currentChar)) {
filteredStringBuilder.append(currentChar);
}
}
return filteredStringBuilder.toString();
}
}
}
答案 0 :(得分:2)
您可以简单地阻止用户输入ISO-8859-1所允许的以外的任何内容。您可以通过将android:digits
属性应用于EditText例如
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "
或通过在每一个新字符传递到视图中时实现自定义过滤器。这样可以确保您只能使用ISO-8859-1字符。
java.nio.charset包中的类CharsetEncoder
提供了检查字符串/字符是否满足特定编码的可能性,
val encoder = Charset.forName("ISO_8859_1").newEncoder()
val canEncode = encoder.canEncode(text)