Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Created November 28, 2014 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NikolaDespotoski/0967cb4c503a9b601dd9 to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/0967cb4c503a9b601dd9 to your computer and use it in GitHub Desktop.
Transformation method that looks for mentions of Twitter-like format in any TextView.
/**
* Created by nikola on 11/28/14.
*/
public class MentionTransformation implements TransformationMethod {
private int mColor;
private Pattern MENTIONS_PATTERN = Pattern.compile("\\B@[a-z0-9_-]+");
private MentionTransformation(int color) {
mColor = color;
}
public static MentionTransformation getInstance(int color) {
return new MentionTransformation(color);
}
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return findMentions(source.toString());
}
@Override
public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction, Rect previouslyFocusedRect) {
}
private SpannableStringBuilder findMentions(String text){
Matcher matcher = MENTIONS_PATTERN.matcher(text);
SpannableStringBuilder spanRange = new SpannableStringBuilder(text);
while(matcher.find()){
String mention = matcher.group();
int startMetion = text.indexOf(mention);
int endMention = startMetion + mention.length();
spanRange.setSpan(new ForegroundColorSpan(mColor), startMetion, endMention, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spanRange;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment