Android:动态更改TextView背景颜色

时间:2011-11-11 06:36:14

标签: android textview background-color

我的活动中有以下textview。我想动态更改textview的背景颜色。

我的问题是我不想从Resouce文件或其他颜色获取颜色.RED方法。我在网络安全模式下从webservie获取颜色(即#FFF,#000等)。

如何将这些颜色作为背景传递给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"/>

6 个答案:

答案 0 :(得分:30)

以下代码段可能会帮助txtChannelName成为TextView的对象

 txtChannelName.setBackgroundColor(Color.RED);

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

答案 1 :(得分:6)

你可以用rbg格式设置android或color的颜色,如下所示:

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

或:

txtView.setBackgroundColor(Color.BLUE);

答案 2 :(得分:4)

您可以尝试:

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

OR

//This is the most preferrable
txt.setBackgroundColor(Color.parseColor("#FF0000"));    

答案 3 :(得分: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);

希望这有帮助。

答案 4 :(得分:1)

您现在可以通过编程方式更改背景颜色。 100% 为我工作。试试吧。

 RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
 relativeLayout.setBackgroundColor(ContextCompat.getColor(yourContext, R.color.yourColor));

稍后谢谢我。

答案 5 :(得分:0)

保存在res / values / colors.xml的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);