Create gradient shade button in android programmatically

Gradient color background for a Button in Android through programming.

Application developer can set gradient effect through MainActivity.java programming file on another button click event or directly shows on activity start time. To make changes on the button to convert it normal button to gradient shade button android gives us GradientDrawable class. So here is the complete step by step tutorial for Create gradient shade button in android programmatically.

android-project-download-code-button

How to Create gradient shade button in android programmatically.

Code for MainActivity.java file.

package com.android_examples.com.gradientbuttonprogrammatically;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class MainActivity extends Activity {

 Button GradientButton;
 // add your choice color here.
 int[] ButtonColors = {Color.parseColor("#04c5fd"),Color.parseColor("#a9e9fb")};
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 GradientButton = (Button)findViewById(R.id.button1);
 GradientDrawable gradientDrawable = new GradientDrawable(
 GradientDrawable.Orientation.BOTTOM_TOP, ButtonColors);
 gradientDrawable.setCornerRadius(0f);
 GradientButton.setBackground(gradientDrawable);
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.gradientbuttonprogrammatically.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="154dp"
 android:text="Sample Button"
 android:textColor="#f8fdf9" />


</RelativeLayout>

Screenshot:

Create gradient shade button in android programmatically

Click Here To Download Create gradient shade button in android programmatically project.

Leave a Reply

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