Setting background colour of Android layout element Setting background colour of Android layout element android android

Setting background colour of Android layout element


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, ..).


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));


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