Skip to content

Instantly share code, notes, and snippets.

@drstranges
Created November 19, 2015 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drstranges/b2ce65f2c2e92d64ec10 to your computer and use it in GitHub Desktop.
Save drstranges/b2ce65f2c2e92d64ec10 to your computer and use it in GitHub Desktop.
public class HashtagEditText extends EditText implements TextWatcher {
private boolean isAddedListener = false;
public HashtagEditText(Context context) {
super(context);
registerListener();
}
public HashtagEditText(Context context, AttributeSet attrs) {
super(context, attrs);
registerListener();
}
public HashtagEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
registerListener();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public HashtagEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
registerListener();
}
private void registerListener() {
if (!isAddedListener) {
isAddedListener = true;
addTextChangedListener(this);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
LinkifyUtils.resetSpans(s, s.length());
LinkifyUtils.setSpans(s, LinkifyUtils.PATTERN_HASHTAG);
}
@Override
public void onTextChanged(CharSequence _text, int start, int before, int count) {}
}
public class LinkifyUtils {
public static final String REGEXP_HASHTAG = "#\\w{1,120}";
public static final Pattern PATTERN_HASHTAG = Pattern.compile(REGEXP_HASHTAG);
public static void setSpans(Editable _text, Pattern pattern){
Matcher matcher = pattern.matcher(_text.toString());
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.RED);
if (_text.getSpans(start, end, ForegroundColorSpan.class).length == 0) {
_text.setSpan(fcs, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
public static void resetSpans(Editable _text, int _length) {
ForegroundColorSpan[] foregroundSpans =
_text.getSpans(0, _length, ForegroundColorSpan.class);
for (ForegroundColorSpan spanToRemove : foregroundSpans) {
_text.removeSpan(spanToRemove);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment