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

我试过这样的方法:

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

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

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


当前回答

Use:

TextView tv = new TextView(this);
tv.setTextColor(Color.rgb(285,0,0));

其他回答

你可以使用

holder.text.setTextColor(Color.rgb(200,0,0));

你也可以用透明度指定你想要的颜色。

holder.text.setTextColor(Color.argb(0,200,0,0));

a代表Alpha(透明)值r-红g-绿b-蓝

如果你在适配器中,仍然想使用在资源中定义的颜色,你可以尝试以下方法:

holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));
   textViewStatus.setTextColor(res.getColor(R.color.green));

为了设置一个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"));

从API 23开始,getResources(). getcolor()已弃用。

用这个代替:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));