Android: How to use custom colors?

I am trying to set the background color of my FrameLayout using my own colors.

I created a .xml file that contains my own colors. Here he is:

 <?xml version="1.0" encoding="utf-8"?> <resources> <color name="red">#FF0000</color> <color name="orange">#FF7D00</color> <color name="yellow">#FFFF00</color> <color name="green">#00FF00</color> <color name="blue">#00B4FF</color> <color name="black">#000000</color> </resources> 

And here is the code where Im trying to set the background color, but when I run the application, FrameLayout always gray, why ?:

 FrameLayout MyFrameLayout = new FrameLayout(this); LayoutParams MyFrameLayoutParam = new LayoutParams(LayoutParams.FILL_PARENT, 200); MyFrameLayout.setLayoutParams(MyFrameLayoutParam); MyFrameLayout.setBackgroundColor(R.color.red); Parent.addView(MyFrameLayout); 
+7
source share
4 answers

Before setting up, you need to get the color from the resources. You assign the identifier R.java not the actual value.

 Color red = getApplicationContext().getResources().getColor(R.color.red) MyFrameLayout.setBackgroundColor(red); 
+9
source

This makes the button a green button, find the color you want.

yourButton.setBackgroundColor (Color.parseColor ("# 25b72f"));

+3
source

To use your own color in xml, you should use something like:

android:color="@color/orange"

+2
source

You can use setBackgroundResource (Color)

Here is an example:

relativelayout.setBackgroundResource(R.color.green);

0
source

All Articles