Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building Android UIs with Custom Views
Building Android UIs with Custom Views

Building Android UIs with Custom Views: Build amazing custom user interfaces with Android custom views

By Raimon Ràfols Montane
NZ$‎57.99
Book Oct 2017 294 pages 1st Edition
eBook
NZ$‎57.99
Print
NZ$‎71.99
Subscription
Free Trial
eBook
NZ$‎57.99
Print
NZ$‎71.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Building Android UIs with Custom Views

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Move beyond default UI templates, create and customize amazing UIs with Android Custom View
  • Enable smooth data flow and create futuristic UIs by creating flexible custom views
  • Scale your apps with responsive and data intensive views

Description

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.

What you will learn

[*]Extend the standard UI widget framework by creating Custom views [*]Add complex rendering, animations, and interactions to your views [*]Optimize performance and decrease battery usage [*]Implement custom views to share between multiple projects, or share it publicly [*]Create 3D custom views using OpenGL ES

Product Details

Country selected

Publication date : Oct 27, 2017
Length 294 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785882869
Vendor :
Google
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Oct 27, 2017
Length 294 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785882869
Vendor :
Google
Category :

Table of Contents

12 Chapters
Preface Chevron down icon Chevron up icon
1. Getting Started Chevron down icon Chevron up icon
2. Implementing Your First Custom View Chevron down icon Chevron up icon
3. Handling Events Chevron down icon Chevron up icon
4. Advanced 2D Rendering Chevron down icon Chevron up icon
5. Introducing 3D Custom Views Chevron down icon Chevron up icon
6. Animations Chevron down icon Chevron up icon
7. Performance Considerations Chevron down icon Chevron up icon
8. Sharing Our Custom View Chevron down icon Chevron up icon
9. Implementing Your Own EPG Chevron down icon Chevron up icon
10. Building a Charts Component Chevron down icon Chevron up icon
11. Creating a 3D Spinning Wheel Menu Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.