Android尝试替换字符并更改单词的颜色 [英] Android trying to replace character and change color of a word

查看:84
本文介绍了Android尝试替换字符并更改单词的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做nota的字符串.有一些文字.我想要的是从其中包含* *的短语中更改特定单词的颜色.例如:太棒了.单词awesome应该具有黄色,并且* *字符应该被擦除(好像*是一种迷你Markdown格式).我尝试了这段代码,但是没有用.我需要帮助.

I have string called nota. There is some texts. What I want is to change the color of specific words from phrase that contains * * between them. Ex.: That is * awesome*. The word awesome should have a yellow color and the * * characters should be erased (as if * is a mini-Markdown formatting). I tried this code, but it didn't work. I need some help.

 if(nota.contains("* *")){

 //nota = nota.replace("* *","");
 Pattern pattern = Pattern.compile("\\*.*\\*");
 Matcher matcher = pattern.matcher(nota);
 // Check all occurrences
 matcher.find();


 Spannable spannable = new SpannableString(nota);
 spannable.setSpan(
 //new ForegroundColorSpan(Color.YELLOW), nota.indexOf("* *"), nota.indexOf("* *") + "* *".length(),     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
 new ForegroundColorSpan(Color.YELLOW), matcher.start() + 1 , matcher.end() - 1,     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 txtnota.setText(spannable);
 }

推荐答案

我是通过以下方式解决的:

I solved it in this way:

if(nota != null){
        int firstIndex = nota.indexOf("*");
        if (firstIndex >= 0) {
            nota = nota.replaceFirst("[*]{1}", "");
            int secIndex = nota.indexOf("*");
            if (secIndex >= 0) {
                nota = nota.replaceFirst("[*]{1}", "");

                Spannable spannable = new SpannableString(nota);
                spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD_ITALIC), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                txtnota.setText(spannable);
            }
        }
}  

这篇关于Android尝试替换字符并更改单词的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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