I am trying to figure out how to limit an edit text field to 140 twitter characters, without allowing the user to type over the limit. I thought I had it working with the code below, however, I discovered it only prevents typing if the cursor is at the end of the editText field. As much as I have tried, I cannot figure out the logic of source and dest, and how to concatenate them into the complete string that would be shown in the editText field. This is what I was attempting to do the the fullTextString.
Note, this is not as simple as limiting the length of the edit text field. Twitter considers a link such as "t.co" as 22 characters, not 3. I haven't seen any other working examples.
A full example to quickly clone is on github here: 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;
}
}
}