如何使用标签更改单词的颜色 [英] How to change color of words with hashtags

查看:61
本文介绍了如何使用标签更改单词的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够显示带有以#开头的所有单词的其他颜色的文本,并且它们应该是可单击的.我该怎么办?

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?

推荐答案

这应该可以解决问题

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);
}

这篇关于如何使用标签更改单词的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆