简体   繁体   English

Android更改字符串的颜色部分

[英]Android change color part of a string

I have a string name "classe". 我有一个字符串名称“ classe”。 It contains many words and phrases in it. 它包含许多单词和短语。 But I want to change color when string contains the word "idiom" . 但是当字符串包含单词"idiom"时,我想更改颜色。 I did that programmatically, but it changed the color of all string "classe". 我以编程方式完成了此操作,但是它更改了所有字符串“ classe”的颜色。 I just want to change the color of "idiom" (a part of word, not the whole phrase). 我只想更改“成语”的颜色(单词的一部分,而不是整个短语)。 How can I do that programmatically? 如何以编程方式做到这一点?

    if (classe.contains("idiom")) {

        txtclasse.setTextColor(getResources().getColor(R.color.orange));
    }

Use ForegroundColorSpan. 使用ForegroundColorSpan。

if(classe != null && classe.contains(“idiom”))
{
    Spannable spannable = new SpannableString(classe);
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), classe.indexOf(“idiom”), classe.indexOf(“idiom”) + “idiom”.length(),     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    txtclasse.setText(spannable);
}

You could use HTML to solve it. 您可以使用HTML来解决它。

origString = txtclasse.getText().toString();
origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");

txtclasse.setText(Html.fromHtml(origString));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 android studio更改autocompletetextview arrayadapter中部分字符串的字体颜色 - android studio change font color of part of string in autocompletetextview arrayadapter Android-在EditText(Highlighting Text)中更改部分字符串的背景颜色 - Android - Change Background Color of a part of String in EditText(Highlighting Text) Android - 如何更改位于 string.xml 中的字符串的一部分的颜色? - Android - How can I change the color of a part of a String located in string.xml? 如何在Android中更改动作栏的颜色 - how to change color of part of actionbar in android Android:无法更改textview中部分文本的颜色 - Android: unable to change color of part of the text in textview Android-有没有办法在显示的字符串的一部分中编辑颜色? - Android - is there a way to edit color in a part of a string that is displayed? 如何在Android中为字符串的某些部分上色? - How to color some part of string in android? 更改图像颜色的一部分 - change part of image color 如何更改字符串中文本格式的一部分(颜色,粗体斜体)? - How to change the part of text format (color,sizebold italic) inside the string? 如何使用 SpannableBuilder 动态更改字符串的一部分颜色 - How to dynamically change part of string's color with SpannableBuilder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM