Created
November 28, 2014 07:27
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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