java 如何改变字符串的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11758927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:15:54  来源:igfitidea点击:

How to change the color of string

javaandroid

提问by Naseeb Sheoran

I am making an application in which i am using strings to diaplay some text on screen.But i want to change the color of the string to red.I don't know how to change the color of string to red.Please tell me how to do it.This is the string:

我正在制作一个应用程序,其中我使用字符串在屏幕上显示一些文本。但我想将字符串的颜色更改为红色。我不知道如何将字符串的颜色更改为红色。请告诉我如何这样做。这是字符串:

strRightAnswer = "Right Answers:" + "  " + String.valueOf(nRightAnswers);

回答by Andro Selva

you have to set the Color of the Text in TextView. Not the String color. It is not valid.

您必须在 TextView 中设置文本的颜色。不是字符串颜色。它无效。

textView.setTextColor(Color.RED);

or Change your String to Html like this,

或像这样将您的字符串更改为 Html,

String s=  "<font color=#00aeef>"+"Right Answers:" + "  " + String.valueOf(nRightAnswers)+"</font>";

and

textView.setText(Html.fromHtml(s));

And find the color code for red and replace it with, color=#00aeeffor the color you want, say red.

并找到红色的颜色代码并将其替换color=#00aeef为您想要的颜色,例如红色。

回答by silentnuke

If you want to change the color is not the entire string, read about spannablestring

如果要更改的颜色不是整个字符串,请阅读有关spannablestring

回答by Yash

Create file res/drawable/text_color.xml:

创建文件 res/drawable/text_color.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" />
    <item android:state_focused="true" android:state_pressed="true" android:color="#ffffff" />
    <item android:state_focused="false" android:state_pressed="true" android:color="#ffffff" />
    <item android:color="#000000" />
</selector>

Then use @drawable/text_color from xml (or R.drawable.text_color from code) as text color for your list view items.

然后使用 xml 中的 @drawable/text_color(或代码中的 R.drawable.text_color)作为列表视图项的文本颜色。