2011-11-11 253 views
7

我在我的Activity中有以下textview。我想動態改變textview的背景顏色。Android:動態更改TextView背景顏色

我的問題是我不想從Resouce文件或其他colors.RED方法獲取顏色。我以Web安全模式(即#FFF,#000等)從webservie獲取顏色。

如何將這些顏色作爲背景傳遞給TextView。在此先感謝您的時間。

<TextView 
       android:id="@+id/colorCode" 
       android:layout_width="40dp" 
       android:layout_height="wrap_content" 
       android:layout_alignParentRight="true" 
       android:layout_alignParentTop="true" android:background="#FF0000" android:layout_marginRight="5dp"/> 

回答

26

下面是摘錄可以幫助你在哪裏txtChannelNameTextView

txtChannelName.setBackgroundColor(Color.RED); 

txtChannelName.setBackgroundColor(Color.parseColor("#ffffff")); 
+1

謝謝,但我已經知道這個方法的。我在我的問題中也提到了這個//顏色來自Resouce文件或其他顏色.RED方法//我想知道我是否可以將#FFF作爲輸入傳遞給textview的背景顏色。 –

+0

更新了答案檢查 – ingsaurabh

+0

謝謝它的作品:) –

2

在您的活動的對象,你做這樣的事情:

TextView textView = (TextView) findViewById(R.id.colorCode); 
int myDynamicColor = Color.parseColor("#FFFF00"); // Here you can pass a string taken from the user or from wherever you want. 
textView.setBackgroundColor(myDynamicColor); 

希望這有助於。

+0

這是我正在談論:) –

4

你可以試試:

String color = "FF0000"; // For example your color is FF0000 
TextView txt = new TextView(this);   
txt.setBackgroundColor(Integer.parseInt(color, 16)+0xFF000000); 

OR

保存在RES /價值/ colors.xml
//This is the most preferrable 
txt.setBackgroundColor(Color.parseColor("#FF0000"));  
0

XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="opaque_red">#f00</color> 
    <color name="translucent_red">#80ff0000</color> 
</resources> 
從你的程序訪問這些顏色像

然後如下:

Resources res = getResources(); 
int color = res.getColor(R.color.opaque_red); 
textView.setBackgroundColor(color); 
5

佑可以從Android或顏色格式RBG設置的色彩是這樣的:

TextView txtView = (TextView) findViewById(R.id.yourId); 
txtView.setBackgroundColor(Color.parseColor("#AA3456")); 

或:

txtView.setBackgroundColor(Color.BLUE);