How to draw a volume button onto a canvas in Android

Perhaps this tutorial will be useful for beginner Android developers.

If you want to create a real TV remote in your app you can create a different types of buttons (for example: d-pad button, volume button, channel button and so on).

This tutorial shows how to draw a volume button. The volume button has capsule shape that need to be divide into two part (the first one is intended to increase volume and the second one is to decrease). If you need a sample, you can look at your TV remote or at the image below.

Thus, this “monolith” button should work like two buttons, depending on which side was pressed.

Let’s look at the code.

Step 1. Draw the capsule

1. Write a method for drawing half of the capsule:

2. Determine the length of each half of the button and form two rounded rectangles for the bottom and top of the button. Сall above method with parameters for drawing the top and bottom half of the capsule to combine them into one.

At this stage, you can see the monolithic volume button as shown below:

Step 2. Add decorations

Moving on. Decorate the button by adding two icons (to the top and bottom parts) and the central text.

1. Draw icons

Define two methods (the first for drawing the “+” icon, the second for drawing the “-” icon) and call them in onDraw(), adding the necessary parameters:

2. Draw text

For adding text we calculate the center of that button and call that method in onDraw():

At this stage we get this image:

Step 3. Add life to the button

Now add clickable effects.

First of all, we overriding method onTouchEvent(). It helps us to define ACTION_UP and ACTION_DOWN events.

For detecting clickable events we define Boolean variables, that can be variate depend on press or release button:

Important thing is to call invalidate() method. If that method doesn’t be called onDraw() method also doesn’t be called.

In the onDraw() method, make changes to the rendering of half the capsule buttons using Boolean variables.

Here we just change one parameter — Paint. It overwrites the previous image, adding a new one.

Step 4. Add beauty

Use gradient:

And getting final result:

You can see the full code by clicking on this link to GitHub:

Hope this tutorial will help someone.:)



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store