Thursday, April 25, 2013

Toggle button with Gradient and Image, Android

To create an android toggle button with a bitmap image and gradient follow the following steps:
1. Create new xml file in drawable-mdpi folder say mybutton.xml.
2. Add gradient and image to this file with selector and layer-list based on behavior you want to achieve. For example:


<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <layer-list >
             <item>
       <shape>
           <solid
               android:color="#a276eb" />
           <stroke
               android:width="3dp"
               android:color="#6a3ab2" />
           <corners
               android:radius="3dp" />
           <padding
               android:left="5dp"
               android:top="5dp"
               android:right="5dp"
               android:bottom="5dp" />
       </shape>
       </item>
       <item>
           <bitmap android:gravity="center_vertical|center_horizontal" android:src="@drawable/dollar" android:tileMode="disabled"/>
       </item>
     
        </layer-list>
    </item>
    <item android:state_checked="false">
        <shape>
            <gradient
                android:startColor="#a276eb"
                android:endColor="#672a7c"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#6a3ab2" />
            <corners
                android:radius="1dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

3. In activity or Fragment where you want to place this button, add a normal button and set background to the custom view that we have defined above as:
android:background="@drawable/mybutton" 
and you are all set.

3 comments:

  1. Excellent post.Its very useful for android developers.

    android app developers India

    ReplyDelete
  2. Hi Aaren, Thanks for you comment but I request you not to post link to your website in comment. I have seen previously such comment. Please avoid in future.

    ReplyDelete
  3. Most comprehensive XML solution for a custom toggle button. Thanks!

    ReplyDelete