How to set the text color of TextView in code?

2018-12-31 10:12发布

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000". But how do I change it by coding?

I tried something like:

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

Where holder is just a class and text is of type TextView. Red is an RGB value (#FF0000) set in strings.

But it shows a different color rather than red. What kind of parameter can we pass in setTextColor()? In documentation, it says int, but is it a resource reference value or anything else?

30条回答
何处买醉
2楼-- · 2018-12-31 10:21

If you plan to use setTextAppearance you should know that it will overwrite the text color with the style inherited from the theme. So if you want to use both, set the color afterwards.

This works:

textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);
textView.setTextColor(Color.RED);

While this will cause your textcolor to be for instance white(for dark theme) or black(for the light theme):

textView.setTextColor(Color.RED);
textView.setTextAppearance(context, android.R.style.TextAppearance_Medium);

Contrary to this in XML the order is arbitrary.

查看更多
临风纵饮
3楼-- · 2018-12-31 10:21
holder.userType.setTextColor(context.getResources().getColor(
                    R.color.green));
查看更多
不再属于我。
4楼-- · 2018-12-31 10:22

In Adapter you can set the text color by using this code:

holder.my_text_view = (TextView) convertView.findViewById(R.id.my_text_view);
holder.my_text_view.setTextColor(Color.parseColor("#FFFFFF"));
查看更多
回忆,回不去的记忆
5楼-- · 2018-12-31 10:22

if you want to give color code directly then use

textView.setTextColor(Color.parseColor("#ffffff"));

or if you want to give color code from colors folder then use

textView.setTextColor(R.color.white);
查看更多
泛滥B
6楼-- · 2018-12-31 10:23

getColor() is depreceted

So try this way:

 tv_title.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.sf_white));
查看更多
弹指情弦暗扣
7楼-- · 2018-12-31 10:23

I was doing this for a TextView in a ViewHolder for a RecyclerView. I'm not so sure why, but it didn't work for me in the ViewHolder initialization.

public ViewHolder(View itemView) {
    super(itemView);
    textView = (TextView) itemView.findViewById(R.id.text_view);
    textView.setTextColor(context.getResources().getColor(R.color.myColor));
    // Other stuff
}

But when I moved it to the onBindViewHolder, it worked fine.

public void onBindViewHolder(ViewHolder holder, int position){
    // Other stuff
    holder.textView.setTextColor(context.getResources().getColor(R.color.myColor));
}

Hope this helps someone.

查看更多
登录 后发表回答