How to create Button with multiple colors in android

In this tutorial we will see how to make a Button with multiple colors. Some applications are having custom button with  two or three colors . In my previous  tutorial How to create button with rounded corners i am explaining how to give background to button using drawable file. We just need to add few more properties to the same drawable  file to make it as custom button with multiple colors.

Steps

  1. Create new project in android studio
  2. Custom drawable for the button
  3. Add the button with custom background to the layout

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Custom drawable for button

We cannot directly set the multiple colors for button in xml .So first you need to have an xml file in your drawable folder with the following code which will be used as the button in layout file.

custom_button_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">

<gradient
android:angle="180"
android:centerColor="@color/colorPrimaryDark"
android:centerX="50%"
android:endColor="@color/colorAccent"
android:startColor="@color/colorPrimary"

></gradient>

<corners android:radius="15dp" />
</shape>
</item>
</selector>

Add the button with custom background to the layout

Now simply use the below button code in your layout file, the button will contain the background as the above created drawable which will allow you to set multiple colors.

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Button"
android:background="@drawable/custom_button_drawable"
android:textColor="@color/white"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:padding="15dp"
/>

 

Here is the colors to added to colors.xml which is using in above code

<color name="colorPrimaryDark">#303F9F</color>
<color name="colorPrimary">#3F51B5</color>
<color name="colorAccent">#FF4081</color>
<color name="white">#FFFFFF</color>

output

android_multicolor-button
android_multicolor-button

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

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