How to use gradient in some Android component?

Question:

How to use gradient effect in some Android component? Like a navigation bar, or a simple TextView ?

Answer:

The XML provides the <gradient> tag on which to perform this feat. Basically you define a start color, a center color (not mandatory) and an end color to accomplish this effect. See below for the following attributes:

  • startColor : initial color
  • centerColor : center color
  • endColor : end color
  • angle : the angle at which it can be rotated, which can be set to 0 , 90 , 180 , 270 .

There are other attributes described in the documentation.

Then a file can be created in the drawable directory for example with the name gradient.xml :

drawable/gradient.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <gradient 
            android:startColor="#6586F0"
            android:centerColor="#D6D6D6"
            android:endColor="#4B6CD6"
            android:angle="90"/>
</shape>

Finally, just set some view as the background, being a Button , TextView , Toolbar , LinearLayout , etc. Look:

android:background="@drawable/gradient"

Application example:

<Button
    android:id="@+id/thebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient"
    android:text="Button Gradient!"
    />
Scroll to Top