Home » Android » java – Android: set color programatically from XML color constants

java – Android: set color programatically from XML color constants

Posted by: admin May 14, 2020 Leave a comment

Questions:

Trying to set a color which is defined in res/values/colors.xml to an 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 not figure out why it is not working,
I tried a lot of approaches (getResources(), Color.parseColor(), ...)

How do I set the color “tableHead” e.g. to a TextView?

tv.setBackgroundColor(????);

How to&Answers:

Color entries should be like this

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

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

Answer:

Use,..

Color.parseColor("#bdbdbd");

like,

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

OR………………….

Get a handle to the root layout used, then set the background color on that. The root layout is whatever you called setContentView with.

// Now get a handle to any View contained
// within the main layout you are using

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

// Find the root view

 View root = someView.getRootView()

// Set the color

  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Answer:

tv.setTextColor(getResources().getColor(R.color.tableHead));

And guess what your colors.xml should be like this

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

Answer:

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 set in textview: Like this

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

Answer:

Try something like this:

tv.setBackgroundResource(Color.parseColor("#ffffff"));

Answer:

Firstly modify your color.xml as 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>

For setting the textview background color you can do like

tv.setBackgroundColor(R.color.tableHead);

Additionally for setting the textview textcolor you can do like

tv_empty.setTextColor(R.color.tableHead)