Saturday, May 23, 2015

How to create a GradientDrawable programmatically in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="@android:color/white"
    >
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create GradientDrawable"
        android:layout_below="@id/iv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.graphics.drawable.GradientDrawable;
import android.graphics.Color;

public class MainActivity extends Activity{

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

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final ImageView iv = (ImageView) findViewById(R.id.iv);
        Button btn = (Button) findViewById(R.id.btn);

        // Set a click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Initialize a new GradientDrawable
                GradientDrawable gd = new GradientDrawable();

                // Set the color array to draw gradient
                gd.setColors(new int[]{
                        Color.RED,
                        Color.GREEN,
                        Color.YELLOW,
                        Color.CYAN
                });

                // Set the GradientDrawable gradient type linear gradient
                gd.setGradientType(GradientDrawable.LINEAR_GRADIENT);

                // Set GradientDrawable shape is a rectangle
                gd.setShape(GradientDrawable.RECTANGLE);

                // Set 3 pixels width solid blue color border
                gd.setStroke(3, Color.BLUE);

                // Set GradientDrawable width and in pixels
                gd.setSize(450, 150); // Width 450 pixels and height 150 pixels

                // Set GradientDrawable as ImageView source image
                iv.setImageDrawable(gd);
            }
        });
    }
}
More android examples