Building Android UIs with Custom Views - Raimon Rafols Montane - E-Book

Building Android UIs with Custom Views E-Book

Raimon Rafols Montane

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Create engaging user experiences and awesome user interfaces using this guide

About This Book

  • 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

Who This Book Is For

This book is for Android developers who want to create great user interfaces and move beyond the basics of the standard UI elements. They must have basic Android development knowledge along with basic Java programming.

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

In Detail

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.

Style and approach

The approach will be that of a step by step practical tutorial. The book will take you through a complete journey, right from creating your first Android view to customizing it to enable it to support any complex app.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 274

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



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

 

 

 

 

Raimon Ràfols Montané

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Building Android UIs with Custom Views

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2017 Production reference: 1241017

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK. ISBN 978-1-78588-286-9www.packtpub.com

Credits

Author

Raimon Ràfols Montané

Copy Editor

Safis Editing

Reviewer

Basil Miller

Project Coordinator

Sheejal Shah

Commissioning Editor

Amarabha Banerjee

Proofreader

Safis Editing

Acquisition Editor

Reshma Raman

Indexer

Rekha Nair

ContentDevelopmentEditor

Sreeja Nair

Graphics

Jason Monteiro

Technical Editor

Leena Patil

Production Coordinator

Melwyn D'sa

About the Author

Raimon Ràfols Montané is a software engineer currently living in the Barcelona area. He has been working on mobile devices since their early stages, ranging from monochrome devices to the current smartphones. During this time, he has 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 an engineering manager at AXA Group Solutions in Barcelona, taking care of all the engineering and development processes, mobile application quality, and leading the R&D team. In the past, he has worked abroad for Imagination Technologies near London and for Service2Media in the Netherlands.

In his spare time, he enjoys taking part in hackathons, photography, and speaking
 at conferences. Raimon has won more than 40 international awards, including AngelHack Barcelona 2015, Facebook World Hack Barcelona. Also, he has secured the second place at JS1k 2016. He was the chairman of the Transforming Industries Summit at the Mobile World Congress Shanghai 2017, where he also spoke about Enterprise Transformation. In addition, he has given talks speaking about Android and Java performance, bytecode, custom views, and entrepreneurship in at several conferences around the world.

In addition, Raimon is the coauthor of Learning Android Application Development, also published by Packt, and he has been the technical reviewer of several other titles, including Mastering Android NDK and Android Things Projects, among others.

Acknowledgements

I'd really like to thank Laia Gomà; without your love, patience, and understanding, this book wouldn't have been possible. Also, I'd like to thank Rafa Cosin and my parents, as without their support and encouragement, I’d not be doing what I do today. I’d also like to thank everyone who inspired my curiosity about real-time computer graphics and performance. Without that inspiration, I wouldn't have started building custom views and I definitely wouldn’t be speaking at conferences about low-level bytecode. Last but not least, I'd like to thank everyone who challenged me and helped me grow in my professional career; people like Enric Agut, Diego Morales, Alfred Ferrer, Carlos Carrasco, Pau Vivancos, Miquel Barceló, David Domingo, Marcel Roorda, Alberto Chamorro, Teun van Run, Tom van Wietmarschen, Josep Cedó, Yves Caseau, Joanne Pupo, Jordi Valldaura, Mathieu Sivade, Chris Jakob, Tomas Kustrzynski, Ramon Salla, Bartłomiej Żarnowski, Radosław Holewa, Inigo Quilez, and all those who I have forgotten to mention here.

About the Reviewer

Basil Miller is the cofounder of Devlight. An Ivano-Frankivsk based leading Android developer, Basil has over 4 years' experience of being a developer, which has endowed him with the opportunity to hold his current position.

His educational background includes a bachelor's degree in computer science, which he enhanced by attending Java SE courses for 1 year. Besides the status of cofounder, organizer, and speaker of GDG Ivano-Frankivsk, Basil is a part of the core team of Devlight. This technical background has enabled him to develop and train some personal skills, such as team organizing, self-employment, and communication.

Since 2014, Android developers all over the world have been watching his progress and using his free products developed in the role of open source Android UI widgets provider. His products are focused on project architecture, adhering to guidelines, code glance, long-lasting integration, and much more. Another significant achievement are his third-party libraries, which have reached the top of the popular trend charts and stayed there for a long time.

During his time working as a part of Devlight, a lot of products for business solutions were projected and organized by Basil. Projects that he usually works on relate to fintech, currency exchange, delivery services, social networks, and payment system SDKs. His personal duties on the afore mentioned projects are UI implementation, structure creation, team leading, and technical support. Therefore, he has gained the following key skills and competencies: a master's degree in UI realization (canvas, animations, and layout framework), mentoring new developers, and strong knowledge of custom views.

Being a cofounder of Devlight, Basil is able and willing to collaborate on work on the new business projects and start-ups. Also, it is easy to contact Basil in order to involve him into projects as a mobile development consultant.

Basil has garnered recognition among coworkers, partners, and developers abroad. So, the business of Devlight and its achievements are associated with the name Basil Miller.

 

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1785882864.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Getting Started

What's a custom view

The need for custom views

Examples on the market

Setting up the environment

Installing development tools

How to set up an emulator

How to set up a real device for developing

Creating our own first custom view

Extending a view

Creating a simple view from scratch

Summary

Implementing Your First Custom View

Measuring and parameterizing our custom view

Measuring our custom view

Parameterizing our custom view

Instantiating custom views

Instantiating custom views from code

Builder pattern

Creating a custom layout

Extending ViewGroup

Basic rendering

Creating the basic circular activity indicator

Summary

Handling Events

Basic event handling

Reacting to touch events

Drag events

Complex layouts

Advanced event handling

Detecting gestures

Summary

Advanced 2D Rendering

Drawing operations

Bitmaps

Using the Paint class

Drawing more primitives

Drawing text

Transformations and operations

Putting it all together

Summary

Introducing 3D Custom Views

Introduction to OpenGL ES

Getting started with OpenGL ES in Android

Drawing basic geometry

Drawing geometry

Adding volume

Adding textures

Loading external geometry

Summary

Animations

Custom-made animations

Timed frame animations

Fixed timestep

Using Android SDK Classes

ValueAnimator

ObjectAnimator

Summary

Performance Considerations

Performance impact and recommendations

The impact of not following the best practices

Code optimization

Mocking up the preview window

Summary

Sharing Our Custom View

Best practices for sharing our custom view

Considerations and recommendations

Configurable

Publishing our custom view

Open sourcing our custom view

Creating a binary artifact

Summary

Implementing Your Own EPG

Building an EPG

EPG basics and animation setup

Interaction

Zooming

Configurations and Extensions

Making it configurable

Implementing callbacks

Summary

Building a Charts Component

Building a basic chart custom view

Margins and padding

Basic implementation

Optimizations and improvements with Paths

Background lines and details

Customizations

Adding advanced features

Real-time updates

Multiple data sets

Zooming and scrolling

Summary

Creating a 3D Spinning Wheel Menu

Creating an interactive 3D custom view

Adding interactions

Improving interactions and animations

Adding actionable callbacks

Customizations

Beyond the basic implementation

Rendering text

Multiple faces

Summary

Preface

Many years ago, before the launch of Android and the iPhone, one of the major concerns was having a central place to purchase and download mobile applications. Nowadays, we manage to solve this issue with widely available centralized application stores such as Google Play, at the expense of application discoverability.

Google Play, like any other mobile application store, is highly saturated. Unless an application does something unique or has something special, it's extremely hard to stand out from the dozens of applications doing approximately the same, or even if they’re completely unrelated.

Increasing marketing spending might temporarily alleviate the issue but, in the long term, applications still need to figure out that unique functionality or that detail that makes them different.

One way to make a distinctive application is to slightly diverge from the Android standard widgets and UI components and include a specific custom view custom menu, or, at the end of the day, anything that makes it exceptional. We should be aware that this doesn't mean we should completely ignore the Android standard widgets and rewrite the whole UI of the application. As with almost everything, do user tests and discover what works and what doesn’t work for them. Explore new options and solve the pains they have, but don't overdo it. Sometimes, creating a particular menu on top of your application might solve navigation problems, or a well-defined animation might communicate the right transition for the application's users.

In this book, we will see how to start building custom views for Android and integrate them into our applications. We’ll see in detail how to interact with them and add animations and comprehensive examples, both using 2D and 3D rendering capabilities. Finally, we will also see how to share our custom views so they can be reused in our enterprise environment, and also how to open source them and make them available to the Android development community.

What this book covers

Chapter 1, Getting Started, explains what custom views are and when we need them, and shows you how to build your first custom view.

Chapter 2, Implementing Your First Custom View, covers in more details about measurement, instantiating, parameterizing, and some basic rendering to start getting a feeling for what we can do with custom views.

Chapter 3, Handling Events, shows the reader how to make a custom view interactive and react to user interactions.

Chapter 4, Advanced 2D Rendering, adds additional rendering primitives and operations and how to combine them to build more complex custom views.

Chapter 5, Introducing 3D Custom Views, as we are not only limited to 2D rendering, this chapter introduces how we can use OpenGL ES to render custom Views in 3D.

Chapter 6, Animations, covers how to add animations to custom views, both by using standard Android components and by doing it ourselves.

Chapter 7, Performance Considerations, exposes some recommendations and best practices when building a custom view and what the impact of not following them could be.

Chapter 8, Sharing Our Custom View, covers how to package and share our custom view and make it publicly available.

Chapter 9, Implementing Your Own EPG, shows how to build a more complex example of a custom view by combining many of the things we’ve seen in the book.

Chapter 10, Building a Charts Component, shows in detail how to build a chart custom view and make it customizable step by step.

Chapter 11, Creating a 3D Spinning Wheel Menu, covers how to build a more complex 3D custom view that can be used as a selection menu.

What you need for this book

In order to follow the examples in this book, you’ll need Android Studio installed. We’ll briefly cover how to install and set up a device emulator in the first chapter. It’s highly recommended to get at least Android Studio 3.0. At the time of writing this book, Android Studio 3.0 is still beta, but stable enough to develop, run, and test all the examples. In addition, our recommendation is to have an Android device to better experience user interactions in the custom views we’ll create, but they will also work in an Android emulator.

Who this book is for

This book is for developers who want to improve their Android application development skills and build an Android application using custom views.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Android-UIs-with-Custom-Views. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

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