android – How to position radial gradient background-ThrowExceptions

Exception or error:

How can I position a radial gradient shape as background in a LinearLayout ? Here is what I presently have :

The shape :

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:endColor="#e6e6e6"
        android:gradientRadius="800"
        android:startColor="#fafaf9"
        android:type="radial"/>
</shape>

The LinearLayout :

<?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/accueil_bg_gradient">
</LinearLayout>

I just want to have my gradient starting from the left upper corner of the screen, and ending at the right lower corner.

Thanks a lot !

How to solve:

You can move the middle of the radial gradient at a different position of the drawable using “centerX” and “centerY” attributes of the gradient. They are a floating point values ranging from 0 to 1.0 where (values of centerX,centerY accordingly) 0,0 is upper left and 1,1 is bottom right corner.

Default is 0.5,0.5 which is the middle of the drawable / assigned space.
Example for a 100px long (radius), black-white gradient whose middle starts at upper left corner would be:

    <shape android:shape="rectangle">
        <gradient
            android:type="radial"
            android:startColor="#ffffff"
            android:endColor="#000000"
            android:gradientRadius="100"
            android:angle="270"
            android:centerX="0"
            android:centerY="0"/>

    </shape>

###

set this as background mybackground.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle" android:layout_width="wrap_content">
            <stroke android:width="10dp" android:color="@color/darkBlue" />
            <solid android:color="#00000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
            <gradient android:startColor="@color/grayBlue"
                android:endColor="@color/lightBlue" android:angle="270"
                android:centerColor="@color/lightBlue" />
            <!-- border width and color -->
            <stroke android:width="1dp" android:color="#FFDDDDDD" />
            <padding android:left="10dp" android:top="8dp" android:right="10dp"
                android:bottom="8dp" />
        </shape>
    </item>

</layer-list>

Leave a Reply

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