Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android LinearGradient XML

Tags:

android

xml

I'm facing a small problem with the LinearGradient definition in XML. What I want is to use the constructor that accepts the array of colors and the array of positions.

This one:

    LinearGradient(float x0, float y0, float x1, float y1,  int[] colors, float[] positions, Shader.TileMode tile) 

How do I pass the array in the XML? Here's the example of XML with gradient definition, but the simple one.

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android">     <gradient         android:startColor="#474946"         android:endColor="#181818"         android:angle="270"/>     <corners android:radius="5dp" /> </shape> 
like image 383
Juriy Avatar asked Mar 14 '11 15:03

Juriy


People also ask

What is gradients in Android?

Designers are trying out different styles and combinations which go best with the Android App. One of the key components of Android being used these days is called GradientDrawable. A GradientDrawable is drawable with a color gradient for buttons, backgrounds, etc.

How do you color a gradient in XML?

To create a gradient color we need to create a . xml file in the drawable folder. So go to app -> res -> drawable and right-click on drawable -> New -> Drawable Resource File and create gradient_drawable. xml file.


2 Answers

Unfortunately, the definition of GradientDrawable with XML does not allow more than three colors.

Take a look at the official reference: http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html.

Example:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android">     <gradient         android:startColor="#474946"         android:centerColor="#ff0000"         android:endColor="#181818"         android:angle="270"/>     <corners android:radius="5dp" /> </shape> 

So, in your case you would add one more color using android:CenterColor. But for more than three colors, you'll even need to do it with Java.

like image 120
Erick Petrucelli Avatar answered Oct 02 '22 09:10

Erick Petrucelli


@Juriy, @ErickPetru:

+1 for ErickPetru's answer. Although I'd like to mention that there is one more feature available: One cannot only specify the centerColor, but also a center offset, which allows for some more flexibility and sometimes helps to avoid the necessity for Java coding.

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle" >     <corners         android:radius="5dp" />     <gradient         android:type="linear"         android:startColor="#FF000000"         android:centerColor="#FF303030"         android:endColor="#FFE0E0E0"         android:centerX="0.2"         android:centerY="0.3"         android:angle="270" /> </shape> 
like image 43
class stacker Avatar answered Oct 02 '22 09:10

class stacker