Wednesday, January 14, 2015

How to programmatically create gradient color background for a Button in Android

activity_main.xml code snippet

<Button
 android:id ="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Button Gradient Background"
 android:padding="15dp"
 android:onClick="perform_action"
 />
MainActivity.java code snippet

public void perform_action(View v)
{
 Button btn = (Button) findViewById(R.id.push_button);

 //Color.parseColor() method allow us to convert
 // a hexadecimal color string to an integer value (int color)
 int[] colors = {Color.parseColor("#008000"),Color.parseColor("#ADFF2F")};

 //create a new gradient color
 GradientDrawable gd = new GradientDrawable(
   GradientDrawable.Orientation.TOP_BOTTOM, colors);

 gd.setCornerRadius(0f);
 //apply the button background to newly created drawable gradient
 btn.setBackground(gd);
}
Imported Class

import android.view.View;
import android.widget.Button;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
More android examples