Rounded button with shadow in Android

  • 1

Rounded button with shadow in Android

Category : Uncategorized

To create a rounded button, we need to create a new shape resource and configure it as shown below. This shape resource has to be assigned to the button as background, and can not only be applied to a button, but also to any component, like text fields, list elements, etc.

Rounded corners

Create the resource file in /res/drawable with “shape” as root element and include the element “corners”. This element has the attribute “radius” to set the value of the radius for all corners. To set different values for different corners, use the attributes “bottomRightRadius”, “bottomLeftRadius”, “topRightRadius” and “topLeftRadius”.

A: rounded button
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<shape android:shape="rectangle"
   <gradient
     android:startColor="@color/drk_button"
     android:endColor="@color/lgt_button"
     android:angle="90">
   </gradient>
   <corners android:radius="20dip" />
  
   <stroke
     android:width="1px"
     android:color="@color/drk_button" />
</shape>

The gradient element is a gradient background and the stroke element configures the border of the button.

Shadow

The next step is to create the shadow. The effect of the shadow can be done by adding a second shape under the original button shape, changing its color to a darker one.

1
2
3
4
5
6
7
<shape android:shape="rectangle"
     <solid android:color="@color/black_alpha"/>
     <corners android:radius="20dip"/>
</shape>

To overlap different items we have to use a “layer-list” resource and include the previous shapes. The shadow should appear in first place and then the original button with some displacement. In this example, we are creating the shadow at the bottom of the button and an offset of 4px.

B: button with shadow
1
2
3
4
5
6
7
8
9
<layer-list
   <item android:drawable="@drawable/shadow"/>
   <item
     android:drawable="@drawable/button"
     android:bottom="4px" /> 
</layer-list>

Compare results

Compare buttons


1 Comment

Mustafij

October 10, 2016 at 10:29 am

nice

Leave a Reply