Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of words with hashtags

I need to be able to display text with all words starting with a # in a different color and they should be clickable. How can i do this?

like image 765
Samantha Avatar asked Mar 10 '14 03:03

Samantha


1 Answers

This should do the trick

private void setTags(TextView pTextView, String pTagString) {
    SpannableString string = new SpannableString(pTagString);

    int start = -1;
    for (int i = 0; i < pTagString.length(); i++) {
        if (pTagString.charAt(i) == '#') {
            start = i;
        } else if (pTagString.charAt(i) == ' ' || pTagString.charAt(i) == '\n' || (i == pTagString.length() - 1 && start != -1)) {
            if (start != -1) {
                if (i == pTagString.length() - 1) {
                    i++; // case for if hash is last word and there is no
                            // space after word
                }

                final String tag = pTagString.substring(start, i);
                string.setSpan(new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        Log.d("Hash", String.format("Clicked %s!", tag));
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        // link color
                        ds.setColor(Color.parseColor("#33b5e5"));
                        ds.setUnderlineText(false);
                    }
                }, start, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                start = -1;
            }
        }
    }

    pTextView.setMovementMethod(LinkMovementMethod.getInstance());
    pTextView.setText(string);
}
like image 197
Rhys Davis Avatar answered Oct 19 '22 04:10

Rhys Davis