Home Mobile Building Android UIs with Custom Views

Building Android UIs with Custom Views

By Raimon Ràfols Montane
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
To build great user interfaces for your Android apps that go beyond the standard UI elements, you need to use custom Android views. With these, you can give your app a distinctive look and ensure that it functions properly across multiple devices. This book will help you construct a great UI for your apps by teaching you how to create custom Android views. You will start by creating your first Android custom view and go through the design considerations. You will then see how the right choices will enable your custom view to perform seamlessly across multiple platforms and Android versions. You will create custom styleable attributes that work with Android XML layouts, learn to process touch events, define custom attributes, and add properties and events to them. By the end of this book, you will be able to create apps with custom views that are responsive and adaptable to make your app distinctive and an instant hit with its users.
Publication date:
October 2017
Publisher
Packt
Pages
294
ISBN
9781785882869

 

Getting Started

You might be wondering what a custom view is; that's alright, we'll cover that and way more in this book. If you've been developing Android applications for a while, you've most probably used the standard Android views or widgets tons of times. These are, for example: TextView, ImageView, Button, ListView, and so on. A custom view is slightly different. To summarize it quickly, a custom view is a view or a widget where we've implemented its behavior ourselves. In this chapter, we'll cover the very basics steps we'll need to get ourselves started building Android custom views and understand where we should use them and where we should simply rely on the Android standard widgets. More specifically, we will talk about the following topics:

  • What's a custom view and why do we need them?
  • How to set up and configure our environment to develop custom views
  • Creating our very own first custom view
 

What's a custom view

As we have just mentioned, a custom view is a view where we've implemented its behavior ourselves. That was an oversimplification, but it was a good way to start. We don't really have to implement its complete behavior ourselves. Sometimes, it can just be a simple detail, or a more complex feature or even the whole functionality and behavior such as interaction, drawing, resizing, and so on. For example, tweaking the background color of a button as a custom view implementation, it's a simple change, but creating a bitmap-based menu that rotates in 3D is a complete different story in development time and complexity. We'll show how to build both of them in this book but, in this chapter, we'll only focus on the very simple example and we'll add more features in the chapters to come.

Throughout the book, we'll be referring both to custom view and to custom layouts. The same definition of custom view can also be applied to layouts, but with the main difference that a custom layout will help us to lay out the items it contains with the logic we create and position them the precise way we would like. Stay tuned, as later on we'll learn how to do so as well!

The layouts are usually known as ViewGroup. The most typical examples and those you probably have heard of and most probably in your applications are: LinearLayout, RelativeLayout, and ConstraintLayout.

To get more information about Android views and Android layouts, we can always refer to the official Android developer documentation:
https://developer.android.com/develop/index.html.

The need for custom views

There are lovely Android applications on Google Play and in other markets: Amazon, built only using the standard Android UI widgets and layouts. There are also many other applications that have that small additional feature that makes our interaction with them easier or simply more pleasing. There is no magic formula, but maybe by just adding something different, something that the user feels like "hey it's not just another app for..." might increase our user retention. It might not be the deal breaker, but it can definitely make the difference sometimes.

Some custom views can cause so much impact that can cause other applications wanting to imitate it or to build something similar. This effect produces a viral marketing of the application and it also gets the developer community involved as many similar components might appear in the form of tutorials or open source libraries. Obviously, this effect only lasts a limited period of time, but if that happens it's definitely worth it for your application as it'll get more popular and well-known between developers because it'll be something special, not just another Android application.

One of the main reasons to create our own custom views for our mobile application is, precisely, to have something special. It might be a menu, a component, a screen, something that might be really needed or even the main functionality for our application or just as an additional feature.

In addition, by creating our custom view we can actually optimize the performance of our application. We can create a specific way of laying out widgets that otherwise will need many hierarchy layers by just using standard Android layouts or a custom view that simplifies rendering or user interaction.

On the other hand, we can easily fall in the error of trying to custom build everything. Android provides an awesome list of widget and layout components that manages a lot of things for ourselves. If we ignore the basic Android framework and try to build everything by ourselves it would be a lot of work. We would potentially struggle with a lot of issues and errors that the Android OS developers already faced or, at least, very similar ones and, to put it up in one sentence, we would be reinventing the wheel.

Examples on the market

We all probably use great apps that are built only using the standard Android UI widgets and layouts, but there are many others that have some custom views that we don't know or we haven't really noticed. The custom views or layouts can sometimes be very subtle and hard to spot.

We'd not be the first ones to have a custom view or layout in our application. In fact, many popular apps have some custom elements in them. Let's show some examples:

The first example will be the Etsy application. The Etsy application had a custom layout called StaggeredGridView. It was even published as open source in GitHub. It has been deprecated since 2015 in favor of Google's own StaggeredGridLayoutManager used together with RecyclerView.

You can check it yourself by downloading the Etsy application from Google Play, but just to have a quick preview, the following screenshot is actually from the Etsy application showing the StaggeredGrid layout:

There are many other potential examples, but a second good example might be the electronic programming guide of Ziggo, one of the largest cable operators in the Netherlands. The electronic programming guide is a custom view rendering different boxes for the TV shows and changing color for what's ahead and behind current time.

It can be downloaded from the Dutch Google Play only, but anyway, the following screenshot shows how the application is rendering the electronic programming guide:

Finally, a third example and a more recently published application is Lottie from Airbnb. Lottie is a sample application that renders Adobe After Effects animations in real time.

Lottie can be downloaded directly from Google Play, but the following screenshot shows a quick preview of the application:

The rendering view and the custom font are examples of custom rendering. For more information about Lottie refer to:
http://airbnb.design/introducing-lottie/.

We've just seen some examples, but there are many more available. A good site to discover them or to see what is available is Android Arsenal:
https://android-arsenal.com/.

 

Setting up the environment

Now that we have had a brief introduction to custom views, why we need them, and some examples on the market, let's get ourselves started building our own. Our first natural step, if we haven't already done so, is to install Android development tools. If you've got Android Studio already installed, you can skip this section and go directly to the action. Most examples in this book will work perfectly with Android Studio 2.3.3, but later chapters will require Android Studio 3.0. At the time of writing, Android Studio 3.0 is still in beta, but it is highly recommended for testing all the examples provided.

Installing development tools

In order to get started creating your own custom views, you only need what you'll normally need to develop Android mobile applications. In this book, we will be using Android Studio, as it's the tool recommended by Google.

We can get the latest version of Android Studio from its official site:
https://developer.android.com/studio/index.html.

Once we've downloaded the package for our computer, we can proceed with the installation:

Now, we can create a new project that we'll use to take our first baby steps on custom views.

After selecting the Application name, the Company Domain, which will be reversed into the application Package name and the Project location, Android Studio will ask us what type of project we want to create:

For this example, we don't need anything too fancy, just phone and tablet and API 21 support is more than enough. Once we've done that, we can add an Empty Activity:

In the case you need help installing Android Studio, there is a step by step guide on the Learning Android Application Development, Packt Publishing or there is always plenty of information on the Android developer documentation site. For more information, refer to:
https://www.packtpub.com/application-development/learning-android-application-development

Now, we are ready to run this app on a device emulator or on a real device.

How to set up an emulator

To set up an emulator we need to run the Android Virtual Device Manager (AVD Manager). We can find its icon on the top bar, just next to the play/stop application icons.

Once we've executed the Android Device Manager, we can add or manage our virtual devices from there, as shown in the following screenshot:

Clicking on Create Virtual Device will give us the opportunity to use one of the Android device definitions or even create our own hardware profile, as shown in the following screenshot:

Once we've selected the hardware, we've got to choose the software, or the system image, that will run on it. Later on, we can add all the combinations we need for testing: multiple different devices, or the same device with different Android version images, or even a combination of both.

The last step is to name our AVD, review our hardware and software selection, and we're set!

How to set up a real device for developing

It is fine to use an emulator for testing and debugging, but sometimes we really want to test or put the application on a real device. There are a few steps we have to do in order to enable development on our device. First, we need to enable our device for development. We can easily do that by just clicking seven times on the Settings -> About menu -> Build Number since Android 4.2. Once we've done this, there will be a new menu option called Developer options. We have multiple options there that we can explore, but what we need right now is to enable USB debugging.

If USB debugging is enabled, we'll see our device and running emulators on the device selection:

 

Creating our own first custom view

Now that we have set up our environment and we can run and debug Android applications on both an emulator and a real device, we can start creating our own first custom view. To keep it simple, we will first easily modify an existing view and we will proceed, later on, to create our own view from scratch.

Extending a view

Using the example from the previous section, or just creating a new project with an Empty Activity if you've skipped it, we will change the TextView with our own implementation.

If we take a look at the default layout XML file, usually called activity_main.xml if you haven't changed it during project creation, we can see there is TextView inside a RelativeLayout:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.packt.rrafols.customview.MainActivity"> 
 
    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Hello World!" /> 
</RelativeLayout> 

Let's change that TextView to a custom class that we will implement just after this:

<com.packt.rrafols.customview.OwnTextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Hello World!" /> 

We've used the com.packt.rrafols.customview package, but please change it accordingly to the package name of your application.

To implement this class, we will first create our class that extends TextView:

package com.packt.rrafols.customview; 
 
import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.TextView; 
 
public class OwnTextView extends TextView { 
 
    public OwnTextView(Context context, AttributeSet attributeSet) { 
        super(context, attributeSet); 
    } 
} 

This class, or custom view, will behave like a standard TextView. Take into consideration the constructor we've used. There are other constructors, but we'll focus only on this one for now. It is important to create it as it'll receive the context and the parameters we defined on the XML layout file.

At this point we're only passing through the parameters and not doing anything fancy with them, but let's prepare our custom view to handle new functionality by overriding the onDraw() method:

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
} 

By overriding the onDraw() method we're now in control of the drawing cycle of the custom view. If we run the application, we'll not notice any difference from the original example as we haven't added any new behavior or functionality yet. In order to fix this, let's do a very simple change that will prove to us that it is actually working.

On the onDraw() method, we'll draw a red rectangle covering the whole area of the view as follows:

@Override 
    protected void onDraw(Canvas canvas) { 
        canvas.drawRect(0, 0, getWidth(), getHeight(), backgroundPaint); 
        super.onDraw(canvas); 
    } 

We can use the getWidth() and getHeight() methods to get the width and height respectively of the view. To define the color and style we'll initialize a new Paint object, but we'll do it on the constructor, as it is a bad practice to do it during the onDraw() method. We'll cover more about performance later in this book:

private Paint backgroundPaint; 
 
    public OwnTextView(Context context, AttributeSet attributeSet) { 
        super(context, attributeSet); 
 
        backgroundPaint= new Paint(); 
        backgroundPaint.setColor(0xffff0000); 
        backgroundPaint.setStyle(Paint.Style.FILL); 
    } 

Here, we've initialized the Paint object to a red color using integer hexadecimal encoding and set the style to Style.FILL so it will fill the whole area. By default, Paint style is set to FILL, but it doesn't hurt to specifically set it for extra clarity.

If we run the application now, we'll see the TextView, which is our own class right now, with a red background as follows:

The following code snippet is the whole implementation of the OwnTextView class. For more details, check the Example01 folder in the GitHub repository for the full project:

package com.packt.rrafols.customview; 
 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Paint; 
import android.util.AttributeSet; 
import android.widget.TextView; 
 
public class OwnTextView extends TextView { 
 
    private Paint backgroundPaint; 
 
    public OwnTextView(Context context, AttributeSet attributeSet) { 
        super(context, attributeSet); 
 
        backgroundPaint = new Paint(); 
        backgroundPaint.setColor(0xffff0000); 
        backgroundPaint.setStyle(Paint.Style.FILL); 
    } 
 
    @Override 
    protected void onDraw(Canvas canvas) { 
        canvas.drawRect(0, 0, getWidth(), getHeight(),
backgroundPaint); super.onDraw(canvas); } }

This example is only to show how we can extend a standard view and implement our own behaviors; there are multiple other ways in Android to set a background color or to draw a background color to a widget.

Creating a simple view from scratch

Now that we've seen how to modify an already existing View, we'll see a more complex example: how to create our own custom view from scratch!

Let's start by creating an empty class that extends from View:

package com.packt.rrafols.customview; 
 
import android.content.Context; 
import android.util.AttributeSet; 
import android.view.View; 
 
public class OwnCustomView extends View { 
     
    public OwnCustomView(Context context, AttributeSet attributeSet) { 
        super(context, attributeSet); 
    } 
     
} 

We will now add the same code as the previous example to draw a red background:

package com.packt.rrafols.customview; 
 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Paint; 
import android.util.AttributeSet; 
import android.view.View; 
 
public class OwnCustomView extends View { 
 
    private Paint backgroundPaint; 
 
    public OwnCustomView(Context context, AttributeSet attributeSet) { 
        super(context, attributeSet); 
 
        backgroundPaint= new Paint(); 
        backgroundPaint.setColor(0xffff0000); 
        backgroundPaint.setStyle(Paint.Style.FILL); 
 
    } 
 
    @Override 
    protected void onDraw(Canvas canvas) { 
        canvas.drawRect(0, 0, getWidth(), getHeight(),
backgroundPaint); super.onDraw(canvas); } }

If we run the application, as we can see in the following screenshot, we'll have a slightly different result from the previous example. This is because in our previous example the TextView widget was resizing to the size of the text. If we remember correctly, we had android:layout_width="wrap_content" and android:layout_height="wrap_content" in our layout XML file. This new custom view we've just created doesn't know how to calculate its size.

Check the Example02 folder in the GitHub repository for the full implementation of this simple example.

 

Summary

In this chapter, we have seen the reasoning behind why we might want to build custom views and layouts, but also, that we have to apply common sense. Android provides a great basic framework for creating UIs and not using it would be a mistake. Not every component, button, or widget has to be completely custom developed, but by doing it so in the right spot, we can add an extra feature that might make our application remembered. Also, we've shown some examples of applications that are already in the market and they're using custom views, so we know we are not alone out there! Finally, we've seen how to set up the environment to get ourselves started and we began taking our own first baby steps on custom views.

In the next chapter, we'll keep adding features; we'll see how to calculate the right size of our custom view and learn more about custom rendering.

About the Author
  • Raimon Ràfols Montane

    Raimon Ràfols is a Software Engineer currently living in the Barcelona area. He has been working on mobile devices since the early ages: from monochrome devices to the current smartphones. In all these years he worked in several areas: B2C/B2E/B2B apps, portals and mobile gaming. Due to this broad experience, he has expertise in many technologies and, especially in UI, build systems and client-server communications. He is currently working as Engineering Manager at AXA Group Solutions in Barcelona, taking care of all the engineering and development processes, mobile application quality and leading a small R&D team. In the past, he has been working abroad for Imagination Technologies near London and for Service2Media in the Netherlands. In his spare time he enjoys taking part in hackathons, photography and giving talks in conferences. Raimon has won more than 40 international awards including AngelHack Barcelona 2015, Facebook World Hack Barcelona and 2nd place at js1k 2016. He has been speaking about Java/Android performance and bytecode, Android custom views and about entrepreneurship in several conferences around the world. I would like to thank my girlfriend for her support and understanding during the late night and lengthy writing weekends. Also, I would like to thank my parents and cousin, as without their support and encouragement, I would not be doing what I do today. Last, but not least, I would like to thank everyone that challenged me and help me grow up during my professional career. People like Carlos Carrasco, Alfred Ferrer, Pau Vivancos, Miquel Barceló, David Domingo, Marcel Roorda, Diego Morales, Alberto Chamorro, Teun van Run, Tom van Wietmarschen, Josep Cedó, Joanne Pupo, Jordi Valldaura, Mathieu Sivade, Chris Jakob, Tomas Kustrzynski, Bartłomiej Żarnowski, Radosław Holewa and those I have forgotten to mention here.

    Browse publications by this author
Latest Reviews (1 reviews total)
Tiene buenas ofertas por compañas.
Building Android UIs with Custom Views
Unlock this book and the full library FREE for 7 days
Start now