【发布时间】:2015-06-11 05:29:32
【问题描述】:
我试图弄清楚如何将编辑文本字段限制为 140 个 twitter 字符,而不允许用户输入超过限制。我以为我可以使用下面的代码,但是,我发现它只会在光标位于 editText 字段的末尾时阻止输入。尽我所能,我无法弄清楚源和目标的逻辑,以及如何将它们连接成将显示在 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;
}
}
}
【问题讨论】:
-
你试过
android:maxLength="140"吗? -
这行不通。示例:“t.co”是 22 个字符,而不是 3 个字符。仅根据感知长度进行过滤是行不通的。