How to create transparency without using image in Android?

By | February 4, 2013

Transparency in a background of a View in android can be achieved in two ways.
1. By providing a transparent image.
2. By providing an XML that has as shape with end, starting and middle color.

This is a sample XML that creates a transparency.
bg_gradiant.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
             <gradient
                android:endColor ="#FFFFFF"
                android:startColor="#AA2F1701"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#C2C2C2" />
            <corners
                android:radius="3dp" />
            <padding android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp"/>
        </shape>
    </item>   
</selector>

Note : By Simply providing a color doesn’t creates transparency.
The trick lies in the 8-digit code for the color.
The thing is that the last 6 letters represent the original color. The first 2 letter determines it’s alpha or Transparency.

The advantages of this type of xml is that.
1. We can have gradient of colors.
2. we can have gradient in any direction.
3. We have have strokes around the image.
4. we can reduce the size of our application without using an image for this transparency.
5. we can provide padding to them.
6. Most importantly we can have rounded corners to which ever view we apply this as background.

This is how it is applied in XML.

android:background="@drawable/bg_gradiant" 

One thought on “How to create transparency without using image in Android?

  1. Pingback: 渐变笔触与透明背景 – FIXBBS

Leave a Reply

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