在XML中,我们可以通过textColor属性设置文本颜色,比如android:textColor="#FF0000"。但是我如何通过编码来改变它呢?

我试过这样的方法:

holder.text.setTextColor(R.color.Red);

其中holder只是一个类,文本类型为TextView。红色是字符串中设置的RGB值(#FF0000)。

但是它显示的不是红色而是另一种颜色。我们可以在setTextColor()中传递什么样的参数?在文档中,它说的是int,但它是资源引用值还是其他什么?


当前回答

我通常对任何视图都这样做:

myTextView.setTextColor(0xAARRGGBB);

在哪里

AA定义alpha(00为透明,FF为不透明) RRGGBB定义了正常的HTML颜色代码(如FF0000表示红色)。

其他回答

为了设置一个TextView的颜色,TextView. settextcolor (R.color.YOURCOLOR)是不够的!

它必须像这样使用-

TextView myText = (TextView) findViewById(R.id.YoutTextViewID);

myText.setTextColor(getResources().getColor(R.color.YOURCOLOR);

OR

myText.setTextColor(Color.parseColor("#54D66A"));
TextView text = new TextView(context);
text.setTextColor(Color.parseColor("any hex value of a color"));

以上代码在我这边工作。这里text是一个需要设置颜色的TextView。

还有一个:

TextView text = (TextView) findViewById(R.id.text);
text.setTextColor(Color.parseColor("#FFFFFF"));

你可以使用textView.setTextColor(Color. black)来使用Color类的任何内置颜色。

你也可以使用textView.setTextColor(Color.parseColor(hexRGBvalue))来定义自定义颜色。

TextView textresult = (TextView)findViewById(R.id.textView1);
textresult.setTextColor(Color.GREEN);