如何在 Android 中设置 TextView 的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3668958/
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-08-20 11:16:22  来源:igfitidea点击:

How to set the color of a TextView in Android?

android

提问by Arun

In the string.xml file I use the following tag

在 string.xml 文件中,我使用以下标记

<color name="mycolor1">#F5DC49</color>

If I use

如果我使用

 textview1.setTextColor(Color.CYAN);

it works, but

它有效,但是

 textview1.setTextColor(R.color.mycolor1);

is not working.

不管用。

How can I use the color defined in the XML file?

如何使用 XML 文件中定义的颜色?

回答by Patrick Cullen

TextView.setTextColor()takes an int representing the color (eg. 0xFFF5DC49) and not the resource ID from the xml file. In an activity, you can do something like:

TextView.setTextColor()接受一个代表颜色的整数(例如 0xFFF5DC49)而不是来自 xml 文件的资源 ID。在活动中,您可以执行以下操作:

   textView1.setTextColor(getResources().getColor(R.color.mycolor))

outside of an activity you'll need a Contexteg.

在活动之外,您需要一个Context例如。

   textView1.setTextColor(context.getResources().getColor(R.color.mycolor))

回答by AnilPatel

 textView1.setTextColor(Color.parseColor("#F5DC49"));

without resources

没有资源

回答by Pratik Butani

context.getResources().getColoris Deprecated.

context.getResources().getColor已弃用。

You need to use ContextCompat.getColor(), which is part of the Support V4 Library(so it will work for all the previous API).

您需要使用ContextCompat.getColor(),它是Support V4 库的一部分(因此它适用于所有以前的 API)。

ContextCompat.getColor(context, R.color.my_color);

You will need to add the Support V4 library by adding the following to the dependenciesarray inside your app build.gradle:

您需要通过将以下内容添加到dependencies应用程序 build.gradle 中的数组来添加 Support V4 库:

compile 'com.android.support:support-v4:23.0.1' # or any version above

If you care about theming, the documentation specifies that the method will use the context's theme:

如果您关心主题,文档指定该方法将使用上下文的主题:

Starting in M, the returned color will be styled for the specified Context's theme

从 M 开始,返回的颜色将为指定的上下文主题设置样式