Created
November 19, 2015 09:06
-
-
Save drstranges/b2ce65f2c2e92d64ec10 to your computer and use it in GitHub Desktop.
This file contains 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
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) {} | |
} |
This file contains 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
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