2010-09-08 67 views
53

在string.xml文件我用下面的標籤如何在Android中設置TextView的顏色?

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

如果我使用

textview1.setTextColor(Color.CYAN); 

它的工作原理,但

textview1.setTextColor(R.color.mycolor1); 

不工作。

如何使用XML文件中定義的顏色?

回答

79

TextView.setTextColor()需要一個表示顏色的int(例如0xFFF5DC49),而不是來自xml文件的資源ID。在活動中,你可以這樣做:

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

外的活動,你需要一個Context如。

textView1.setTextColor(context.getResources().getColor(R.color.mycolor)) 
20
textView1.setTextColor(Color.parseColor("#F5DC49")); 

沒有資源

12

context.getResources().getColor已被棄用。

您需要使用ContextCompat.getColor(),這是支持V4圖書館的一部分(所以它會爲所有以前的API工作)。

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

您將需要通過添加下面的dependencies陣列您的應用程序的build.gradle裏面添加了支持V4庫:

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

如果你關心的主題化,文檔指定方法將使用上下文的主題:

併購開始,返回的顏色將風格指定的 背景下的主題