Setting background colour of Android layout element
Asked Answered
K

9

206

I am trying to, somewhat clone the design of an activity from a set of slides on Android UI design. However I am having a problem with a very simple task.

I have created the layout as shown in the image, and the header is a TextView in a RelativeLayout. Now I wish to change the background colour of the RelativeLayout, however I cannot seem to figure out how.

I know I can set the android:background property in the RelativeLayout tag in the XML file, but what do I set it to? I want to define a new colour that I can use in multiple places. Is it a drawable or a string?

Additionally I would expect there to be a very simple way to this from within the Eclipse Android UI designer that I must be missing?

I am a bit frustrated currently, as this should be an activity that is performed with a few clicks at maximum. So any help is very appreciated. :)

Android activity design

Kitchener answered 11/9, 2011 at 13:48 Comment(2)
what software did you use to draw the graph on the right side?Blasien
@lucas: I did not draw the diagrams, as I noted in the questions, it is from a set of slides on Android UI design. See the link in the question.Kitchener
P
283

You can use simple color resources, specified usually inside res/values/colors.xml.

<color name="red">#ffff0000</color>

and use this via android:background="@color/red". This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via getResources().getColor(R.color.red).

You can also use any drawable resource as a background, use android:background="@drawable/mydrawable" for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).

Paramorph answered 11/9, 2011 at 14:2 Comment(8)
Works like a charm, thanks. Could you point me to the reference where I should have read this?Kitchener
Uhh actually: No. Just searched the docs, this is pretty standard android stuff, but seems nowhere really documented. Neither the tutorials on the dev site nor the api samples make use of this. The android doc is somewhat lacking when it comes to some features. I think I picked it up by accident in some external tutorials. Usually it's a good idea to browse the api samples and sample projects though. You can find the code inside the ANDROID_SDK\samples folder (for various android versions). The whole api sample app comes also preinstalled in every emulator instance.Paramorph
Also just checked the UI designer. Nothing easy to be found. But I recommend writing things by hand in the xml anyway. The designer improved a lot recently, but it's still not useable in my opinion. Not only are some options limited, the layout sometimes looks completely different on a real device (especially when using referenced drawable resources. They don't get scaled correctly or are even not displayed at all in my experience). Test your layouts on your device or on an emulator.Paramorph
for some "default" colors, you can use this syntax: android:background="@android:color/white"Mandel
You can use the color string directly in the layout element: android:background="#f00" (or any of the other color string formats with more digits).Jeopardy
getResources().getColor() is deprecated now.Nonprofit
@RohitBandil What should we use now?Tetroxide
Hello, I set the background color of screen to blue. But some times it display black. why this happen ? please help me.Fancie
L
96

The above answers are nice.You can also go like this programmatically if you want

First, your layout should have an ID. Add it by writing following +id line in res/layout/*.xml

<RelativeLayout ...
...
android:id="@+id/your_layout_id"
...
</RelativeLayout>

Then, in your Java code, make following changes.

RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);

apart from this, if you have the color defined in colors.xml, then also you can do programmatically :

rl.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.red));
Lecce answered 11/9, 2011 at 14:24 Comment(8)
If you want it dynamic, I think you cannot use XML.Zap
+1 for I need to change it at runtime according to status flag; I was also able to get original color back by using the Color.TRANSPARENT constant.Butchery
@BjarkeFreund-Hansen He acknowledges the other answers and provides this programmatic solution. Not downvote worthy.Tapestry
@AnubianNoob: I disagree. The question is on how to define a colour in markup, and the original answer was how to set a static hard-coded color value. So the answer specifically did not answer the question. With the latest edit to the answer, it is more relevant, but that was made after my comment.Kitchener
@BjarkeFreund-Hansen, the question is how to set the background not how to define color, read properly. And so what if the question is on that. I acknowledge that and told "you can also go like"....so he may go or may not. Also it may help others as it already did you can see. can you ??Lecce
@AndroidKiller: Question specifically states: "I want to define a new colour that I can use in multiple places.". The problem I see is that this answer (along with several of the others) confuses the reader, in that it is very specifically not an answer to what is being asked. I bet there are several other questions where this is the perfect answer, so it should be posted there instead. This is becoming a meta discussion, and if you really believe my -1 vote is a general problem that should be discussed, then please create a meta question and I will answer there.Kitchener
plus one just to compensate the minus one from @BjarkeFreund-HansenJezebel
if i want to change list rows color randomly we can use it, thanksMaestro
I
46

You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

Incredulous answered 11/9, 2011 at 13:57 Comment(2)
-1 because I explicitly wrote "I want to define a new colour that I can use in multiple places" in the question, because I did not want to hardcode the color value, but define it as a resource I can use in several places.Kitchener
@GMsoF: Oh it does work but it does not answer the question.Kitchener
J
23

The

res/values/colors.xml.

<color name="red">#ffff0000</color>
android:background="@color/red"

example didn't work for me, but the

android:background="#(hexidecimal here without these parenthesis)"

worked for me in the relative layout element as an attribute.

Jesse answered 8/8, 2013 at 23:36 Comment(1)
Did you forget to wrap the color tag with a resources tag?Anchovy
A
21

If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:

android:background="@android:color/black"

There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.

Setting up a values/colors.xml file and using straight Hex like explained above will still work.

Ailey answered 29/11, 2014 at 16:15 Comment(0)
S
9

4 possible ways, use one you need.

1. Kotlin

val ll = findViewById<LinearLayout>(R.id.your_layout_id)
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))

2. Data Binding

<LinearLayout
    android:background="@{@color/white}"

OR more useful statement-

<LinearLayout
    android:background="@{model.colorResId}"

3. XML

<LinearLayout
    android:background="#FFFFFF"

<LinearLayout
    android:background="@color/white"

4. Java

LinearLayout ll = (LinearLayout) findViewById(R.id.your_layout_id);
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
Sinecure answered 4/2, 2019 at 9:23 Comment(0)
L
2

Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:

Color Wheel in Android Studio

I got this by adding the following to my layout:

android:background="#FFFFFF"

Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.

Lauro answered 8/8, 2016 at 14:10 Comment(0)
C
1

Kotlin

linearLayout.setBackgroundColor(Color.rgb(0xf4,0x43,0x36))

or

<color name="newColor">#f44336</color>

-

linearLayout.setBackgroundColor(ContextCompat.getColor(vista.context, R.color.newColor))
Christianechristiania answered 23/11, 2018 at 13:42 Comment(0)
C
0

The answers above all are static. I thought I would provide a dynamic answer. The two files that will need to be in sync are the relative foo.xml with the layout and activity_bar.java which corresponds to the Java class corresponding to this R.layout.foo.

In foo.xml set an id for the entire layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/foo" .../>

And in activity_bar.java set the color in the onCreate():

public class activity_bar extends AppCompatActivty {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.foo);

            //Set an id to the layout
        RelativeLayout currentLayout = 
                    (RelativeLayout) findViewById(R.id.foo);

        currentLayout.setBackgroundColor(Color.RED);
        ...
    }
    ...
}

I hope this helps.

Cloudcapped answered 5/9, 2018 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.