android: How to use custom colors?
Asked Answered
N

4

9

Im trying to set the backgroundcolor of my FrameLayout using my own colors.

I created a .xml file which contains my own colors. Here it 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 backgroundcolor, but when I run the app, the FrameLayout is always grey, 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);
Nedneda answered 7/9, 2012 at 21:56 Comment(0)
C
11

You need to retrieve the color from resources before setting it. You are assigning the R.java id not the actual value.

Color red = getApplicationContext().getResources().getColor(R.color.red)
MyFrameLayout.setBackgroundColor(red);
Compton answered 7/9, 2012 at 21:59 Comment(1)
I think it's R.color.red instead of R.id.redRael
J
3

To use your custom colour in xml, you would use something like:

android:color="@color/orange"

Jahn answered 8/11, 2014 at 15:56 Comment(0)
R
3

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

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

Radarman answered 11/12, 2014 at 10:10 Comment(0)
O
1

You can use setBackgroundResource(Color)

Here an example:

relativelayout.setBackgroundResource(R.color.green);

Overbuild answered 20/11, 2013 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.