How to change color of words with hashtags

后端 未结 1 1163
闹比i
闹比i 2021-01-02 16:19

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?

相关标签:
1条回答
  • 2021-01-02 17:07

    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);
    }
    
    0 讨论(0)
提交回复
热议问题