Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the background colour of a Layout view to a gradient in Android?

How do I specify that the background "colour" of a Android layout view element should be a gradient (at a specific angle) ?

I wish to specify this in the XML, i.e. not at runtime. Preferably as a style I can apply to any layout I wish with the style property?

like image 666
Bjarke Freund-Hansen Avatar asked Sep 12 '11 13:09

Bjarke Freund-Hansen


People also ask

How do I change the background color in layout?

android:background="" is the attribute used to set background for any Layout file. You can directly specify the value as HEX color code as we do for CSS files in HTML. You can also add transparency to the color by adding 2 more hex numbers after the # (hash) symbol.


2 Answers

create gradient.xml in /res/drawable:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle">     <gradient         android:startColor="#FFFFFF"         android:endColor="#00000000"         android:angle="45"/>     </shape> 

and in your main.xml layout file in /res/layout:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:background="@drawable/gradient"     >    </LinearLayout> 

you can specify the angle by replacing the android:angle value and start/end colour by replacing android:startColor and android:endColor

like image 60
DonGru Avatar answered Sep 21 '22 23:09

DonGru


You can use something like this:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"         android:shape="rectangle">     <gradient android:startColor="#A1A1A1"                android:centerColor="#BDBDBD"               android:endColor="#A4A4A4"                android:angle="-90" /> </shape> 

to build a gradient (You choose the colors you like ). Place this in drawable and voila you got your own shape to use as background: android:background="@drawable/the_name_of_your_xml"

like image 30
Aurelian Cotuna Avatar answered Sep 19 '22 23:09

Aurelian Cotuna