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

Aru*_*run 55 android

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

<color name="mycolor1">#F5DC49</color>
Run Code Online (Sandbox Code Playgroud)

如果我使用

 textview1.setTextColor(Color.CYAN);
Run Code Online (Sandbox Code Playgroud)

它有效,但是

 textview1.setTextColor(R.color.mycolor1);
Run Code Online (Sandbox Code Playgroud)

不管用.

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

Pat*_*len 82

TextView.setTextColor()采用表示颜色的int(例如0xFFF5DC49)而不是xml文件中的资源ID.在活动中,您可以执行以下操作:

   textView1.setTextColor(getResources().getColor(R.color.mycolor))
Run Code Online (Sandbox Code Playgroud)

在一项活动之外你需要一个Context例如.

   textView1.setTextColor(context.getResources().getColor(R.color.mycolor))
Run Code Online (Sandbox Code Playgroud)


Ani*_*tel 21

 textView1.setTextColor(Color.parseColor("#F5DC49"));
Run Code Online (Sandbox Code Playgroud)

没有资源


Pra*_*ani 13

context.getResources().getColor 已弃用.

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

ContextCompat.getColor(context, R.color.my_color);
Run Code Online (Sandbox Code Playgroud)

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

compile 'com.android.support:support-v4:23.0.1' # or any version above
Run Code Online (Sandbox Code Playgroud)

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

从M开始,返回的颜色将针对指定的Context主题设置样式