Android: set color programmatically from XML color constants

Trying to set the color that is defined in the res / values ​​/colors.xml object,

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <drawable name="listViewSelected">@android:color/holo_blue_light</drawable>
  <drawable name="listViewPressed">@android:color/holo_green_light</drawable>
  <drawable name="pagerTabStrip">#2B3333</drawable>
  <!--<drawable name="pagerTabStrip">#353F3E</drawable>-->
  <drawable name="tableHead">#FF444444</drawable>

</resources>

I can’t understand why it doesn’t work, I tried many approaches (getResources(), Color.parseColor(), ...)

How to set the color "tableHead", for example. in a textview?

tv.setBackgroundColor (????);

+4
source share
6 answers

Color entries should be like this

<color name="tableHead">#FF444444</color>

and use tv.setBackgroundResource(R.color.tableHead);

+8
source

Using,..

Color.parseColor("#bdbdbd");

as

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

OR......................

Get the handle to the root layout used, then set the background color for it. The root layout is what you called setContentView with.

// , // ,

 View someView = findViewById(R.id.randomViewInMainLayout);

//

 View root = someView.getRootView()

//

  root.setBackgroundColor(getResources().getColor(android.R.color.red));
+3
tv.setTextColor(getResources().getColor(R.color.tableHead));

And guess what your color.xml should be like that

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="tableHead">#FF444444</color>
</resources>
+2
source

Try something like this:

tv.setBackgroundResource(Color.parseColor("#ffffff"));
+1
source

First change your .xml color below

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="listViewSelected">@android:color/holo_blue_light</drawable>
  <color name="listViewPressed">@android:color/holo_green_light</drawable>
  <color name="pagerTabStrip">#2B3333</drawable>
  <!--<color name="pagerTabStrip">#353F3E</drawable>-->
  <color name="tableHead">#FF444444</drawable>

</resources>

To set the background color of a text field, you can do, for example,

tv.setBackgroundColor(R.color.tableHead);

Additionally, to set the text color for textview, you can do, for example,

tv_empty.setTextColor(R.color.tableHead)
+1
source

Your color.xml should look like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="tableHead">#FF444444</color>
</resources>

How you will use this color to install in text form: Like this

tv.setBackgroundColor(getResources().getColor(R.color.tableHead));
0
source

Source: https://habr.com/ru/post/1584172/


All Articles