Android UI

How To Give Gradient Effect To The Page Using XML

Similar PhotoShop Gradient Tool

linear_gradient

In Android we have the ability to create gradient effect to a view. This method does not require image creation.
All we have to do is to create a gradient drawable and set it as the source or background of the view.

Gradient Drawable

Like a photoshop gradient tool, Gradient Drawable too has the following options.

  1.  Shape – line, oval, rectangle, ring
  2.  Angle – 0 to 360 degree
  3.  Start color – starting hexa decimal code
  4. End color – ending hexa decimal code
  5. Type – linear, radial, sweep

The shape drawable with the above attributes is known as a Gradient Drawable which can give a color gradient effect to any type of view which has src/background attribute.

Let’s Create Gradient Drawable

res/drawable/gradient_bg.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient android:angle="90" android:endColor="#4a80ec" android:startColor="#14316b" android:type="linear" />
</shape>

Activity Layout XML

res/layout/activity_main.xml

Add android:background="@drawable/gradient_bg" to the layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="gradientbg.devdeeds.com.gradientbackground.MainActivity" android:background="@drawable/gradient_bg" />

MainActivity Class

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Run The App

screenshot_gradient_bg

Advantages

  • APK will be in less size
  • Don’t need graphic designer help
  • Easily modifiable as it defined as name value pairs.
About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *