Android: 动态更改 TextView 的背景颜色

11
我在我的Activity中有一个TextView,我想动态更改它的背景颜色。
我的问题是我不想从资源文件或其他colors.RED方法中获取颜色。我在websafe模式下从webservice获取颜色(即#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个回答

35

以下代码片段可能会对你有所帮助,其中txtChannelName是一个TextView对象。

 txtChannelName.setBackgroundColor(Color.RED);
或者
txtChannelName.setBackgroundColor(Color.parseColor("#ffffff"));

1
谢谢,但我已经知道这种方法了。我在问题中也提到了这个//从资源文件中获取颜色或使用其他colors.RED方法//。我想知道是否可以将#FFF作为输入传递给textview的背景颜色?? - Jay Mayu

8
您可以从 Android 或 RGB 格式设置颜色,如下所示:

您可以从 Android 或 RGB 格式设置颜色,如下所示:

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

或者:

txtView.setBackgroundColor(Color.BLUE);

4
你可以尝试以下方法:
String color = "FF0000";   // For example your color is FF0000
TextView txt = new TextView(this);         
txt.setBackgroundColor(Integer.parseInt(color, 16)+0xFF000000);

或者

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

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);

希望这能帮到你。

这就是我所说的 :) - Jay Mayu

1

现在你可以通过编程来更改背景颜色。对我来说100%有效。试试看。

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

稍后感谢我。


0

XML文件保存在res/values/colors.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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接