Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set text color to a text view programmatically [duplicate]

How can I set the text color of a TextView to #bdbdbd programatically?

like image 657
Noby Avatar asked Dec 12 '11 09:12

Noby


People also ask

How do I set color programmatically?

We can get the reference to TextView widget present in layout file and change the color dynamically with Kotlin code. To set the color to the TextView widget, call setTextColor() method on the TextView widget reference with specific color passed as argument. setTextColor() method takes int as argument. Use android.


2 Answers

Use,..

Color.parseColor("#bdbdbd"); 

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd")); 

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>)); 

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>)); 
like image 68
user370305 Avatar answered Sep 25 '22 16:09

user370305


Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color)); 

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color)); 

where the required color is defined in an xml as:

<resources>   <color name="some_color">#bdbdbd</color> </resources> 

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

like image 26
AlikElzin-kilaka Avatar answered Sep 23 '22 16:09

AlikElzin-kilaka