3

Apologies if this is a duplicate question but I'm struggling to find the syntax needed to do what I want.

I have an attributes file in my resources where i store a bunch of different colours, and have been settings them in xml like so:

android:textColor="?attr/textcolor"

Say I have a TextView called textView in my Java. How can I do the same task programmatically? I'm thinking it must be something similar to:

textView.setTextColor(getResources().getColor(...))

But I can't figure out exactly what I need to write.

Cheers

Mohamad Rostami
  • 420
  • 3
  • 17
Roonil
  • 486
  • 1
  • 4
  • 13
  • Have you checked with `R.color.textcolor`? – Jeel Vankhede Sep 29 '18 at 02:56
  • @JeelVankhede, yes, it says it can not resolve symbol textcolor. I think it's looking for it in my colors.xml file, but I need it to look in my attr.xml file, hence I am wondering what the syntax is. – Roonil Sep 29 '18 at 03:00
  • It would be `R.attr` but you won't be able to set color from it *(because it wouldn't find in it)*, i would suggest you put color into `colors.xml` – Jeel Vankhede Sep 29 '18 at 03:07
  • @JeelVankhede I'm using R.attr because I have a day and night mode, and the attr file sets the names of the different styles in my styles file, where the colours are stored. – Roonil Sep 29 '18 at 03:20
  • possible duplicate of https://stackoverflow.com/a/27611244/7319704 – Abhinav Gupta Sep 29 '18 at 04:59

3 Answers3

2

Try this,

int[] attrs = {R.attr.textcolor};
TypedArray typedArray = context.obtainStyledAttributes(attrs);
int color = typedArray.getResourceId(0, android.R.color.black);
typedArray.recycle();

textView.setTextColor(color);
Saikrishna Rajaraman
  • 3,205
  • 2
  • 16
  • 29
1

First define Color you want to set on Textview via color.xml file, for example ->

<color name="colorPrimary">#3F51B5</color>

Then inside your java file, This single line will set color on textview, note that the color will be fetched from defined colors inside color.xml file. ->

textView.setTextColor(getResources().getColor(R.color.colorPrimary));
Jay Dangar
  • 3,271
  • 1
  • 16
  • 35
0

you should use the view that has been cast from the TextView class not the TextView class itself. use

TextView textView = (TextView)findViewById(...);
textView.setTextColor(getResource().getColor(R.color.black

));

then store your colors in color.xml file not attributes, unless you want to use something more than only color

example

<color name="black">#000000</color>
Mohamad Rostami
  • 420
  • 3
  • 17