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 Radial"
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.WHITE,
Color.YELLOW
});
// Set the GradientDrawable gradient type linear gradient
gd.setGradientType(GradientDrawable.RADIAL_GRADIENT);
/*
setGradientRadius(float gradientRadius)
Sets the radius of the gradient.
*/
gd.setGradientRadius(150);
/*
setGradientCenter(float x, float y)
Sets the center location of the gradient.
*/
//gd.setGradientCenter(0,0);
// Set GradientDrawable shape is a rectangle
gd.setShape(GradientDrawable.RECTANGLE);
// Set 2 pixels width solid black color border
gd.setStroke(2, Color.BLACK);
// Set GradientDrawable width and in pixels
gd.setSize(200, 200); // Width 400 pixels and height 100 pixels
// Set GradientDrawable as ImageView source image
iv.setImageDrawable(gd);
}
});
}
}

