Skip to content

Instantly share code, notes, and snippets.

@Sirelon
Last active May 31, 2016 15:34
Show Gist options
  • Select an option

  • Save Sirelon/079d055aa79a3ec3c186c7f05e77eb32 to your computer and use it in GitHub Desktop.

Select an option

Save Sirelon/079d055aa79a3ec3c186c7f05e77eb32 to your computer and use it in GitHub Desktop.
class, which handle and show hashtags into textView.
package com.sirelon;
import android.support.annotation.ColorInt;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author romanishin
* @since 31.05.16.
*/
public class HashtagsText {
private int color;
private OnHashTagClick mListener;
private boolean withUnderLine;
public HashtagsText() {
}
public HashtagsText callback(HashtagsText.OnHashTagClick listener) {
this.mListener = listener;
return this;
}
public HashtagsText color(@ColorInt int color) {
this.color = color;
return this;
}
public HashtagsText withUnderLine(boolean value) {
this.withUnderLine = value;
return this;
}
public void setHastags(TextView textView, String text) {
if (TextUtils.isEmpty(text)) {
return;
}
textView.setMovementMethod(LinkMovementMethod.getInstance());
//Pattern to find if there's a hash tag in the message
//i.e. any word starting with a # and containing letter or numbers or _
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
ClickableSpan clickableSpan;
int start;
int end;
SpannableString spannableString = new SpannableString(text);
Matcher matcher = tagMatcher.matcher(text);
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
final CharSequence hashTag = text.subSequence(start, end);
clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
if (mListener != null)
mListener.onHasTagClick(hashTag);
}
@Override
public void updateDrawState(TextPaint ds) {
if (color != -1)
ds.setColor(color);
ds.setUnderlineText(withUnderLine);
}
};
spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textView.setText(spannableString);
}
public interface OnHashTagClick {
void onHasTagClick(CharSequence hastag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment