基于Tweet长度的java文本过滤
我试图找出如何将编辑文本字段限制为140个twitter字符,而不允许用户键入超过限制的内容。我想我已经使用了下面的代码,但是,我发现只有当光标位于editText字段的末尾时,它才能阻止键入。尽管我已经尝试了很多,但我无法理解source和dest的逻辑,以及如何将它们连接到editText字段中显示的完整字符串中。这就是我试图对fullTextString执行的操作
注意,这并不像限制编辑文本字段的长度那么简单。Twitter认为像“t.co”这样的链接是22个字符,而不是3个。我没有看到任何其他有效的例子
github上有一个快速克隆的完整示例: https://github.com/tylerjroach/TwitterEditTextLengthFilter
public class TwitterLengthFilter implements InputFilter {
Validator tweetValidator = new Validator();
private final int max;
public TwitterLengthFilter(int max) {
this.max = max;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
String destString = dest.subSequence(0, dstart).toString();
String sourceString = source.subSequence(start, end).toString();
String fullTextString = destString + sourceString;
if (fullTextString.length() == 0) {
return "";
} else if (tweetValidator.getTweetLength(fullTextString) <= max) {
return null; //keep original
} else {
CharSequence returnSource = "";
for (int i=0; i<sourceString.length(); i++) {
if (tweetValidator.getTweetLength(destString + source.subSequence(0, i + 1)) <= max) {
returnSource = source.subSequence(0, i + 1);
}
}
return returnSource;
}
}
}
# 1 楼答案
尝试将其添加到编辑文本XML中:
# 2 楼答案
在阅读了更多关于过滤方法的内容后,我终于能够理解它。我相信它会更有效率,但目前它还有效。我希望有任何建议能让它变得更好