Android / Programming

Custom buttons with Android

Out of the box, android buttons are… Not very pretty. Useful? sure. They do the job. But they aren’t getting any design awards.

Where does it all happen

Custom buttons are not defined in the style section. Android buttons are defined in the drawable folder, as an asset, using a xml file.

The XML file sections

The first section is the selector. This is the main item (and only item if you’re defining only a single item per file as you should). Using Android studio, right click on the the drawable folder ->new->Drawable Resource file will produce a dialog prompting you to choose a name, and already setting the root element as selector.

The item section

This you have to do on your own; every item represents a state (and not another view) of a view, in this case, our button. start typing state and you should get a lot of options:

As we’re interested in buttons, the state that interests us is pressed, both false (not) and true (user pressing it):

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false"> </item> <item android:state_pressed="true"> </item> </selector>
Code language: C# (cs)

Within each of the two we can define colors, roundness borders and so on. In this case we have just one item inside of item, shape (here is the entire file):

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false"> <shape android:shape="rectangle"> <corners android:radius="@dimen/button_radius_regular"></corners> <solid android:color="@color/button_major_color"></solid> <padding android:bottom="@dimen/button_padding_regular" android:left="@dimen/button_padding_regular" android:right="@dimen/button_padding_regular" android:top="@dimen/button_padding_regular" /> </shape> </item> <item android:state_pressed="true"> <shape android:shape="rectangle"> <corners android:radius="@dimen/button_radius_regular"></corners> <solid android:color="#5EA0A8"></solid> <padding android:bottom="@dimen/button_padding_regular" android:left="@dimen/button_padding_regular" android:right="@dimen/button_padding_regular" android:top="@dimen/button_padding_regular" /> </shape> </item> </selector>
Code language: C# (cs)

This is a basic file, and there is a lot more that you can add: color, sizes lines and so on.

Assigning a style to a button

Surprisingly, you do not use the style directive, but the background one:

android:background="@drawable/my_button"
Code language: JavaScript (javascript)

Creating round buttons

To create a round button, you need to do 2 things:

  1. change the shape to “oval”.
  2. make sure that the width and the height are the same.

If the height and width are not the same, you’ll have an oval, which you might want to use from time to time.

Leave a Reply

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