Material Design Android
Material Design Android
Material Design Android
Interface Design
ooks in the HCI and Usability series provide practicing programmers with
unique, high-quality references and tutorials on interaction and interface
design, a critical component of success for any mobile app or website. The books
in this series bring the full range of methods and options available to meet the
challenge of designing for a natural and intuitive global user experience.
Android User
Interface Design
Implementing Material Design
for Developers
Second Edition
Ian G. Clifton
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and the
publisher was aware of a trademark claim, the designations have been printed with initial
capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding interests), please contact our
corporate sales department at corpsales@pearsoned.com or (800) 382-3419.
For government sales inquiries, please contact governmentsales@pearsoned.com.
For questions about sales outside the U.S., please contact international@pearsoned.com.
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2015950113
Copyright 2016 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected
by copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. To obtain permission to
use material from this work, please submit a written request to Pearson Education, Inc.,
Permissions Department, 200 Old Tappan Road, Old Tappan, New Jersey 07675, or you
may fax your request to (201) 236-3290.
Google is a registered trademark of Google, Inc.
Android, Chromecast, Gmail, Google Maps, Google Play, and Nexus are trademarks of
Google, Inc.
Amazon and Kindle Fire are registered trademarks of Amazon.com, Inc.
Java is a registered trademark of Oracle and/or its affiliates.
Illustrator and Photoshop are registered trademarks of Adobe Systems Incorporated.
ISBN-13: 978-0-134-19140-9
ISBN-10: 0-134-19140-4
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing: November 2015
Editor-in-Chief
Mark Taub
Executive Editor
Laura Lewin
Development Editor
Songlin Qiu
Managing Editor
Kristy Hart
Project Editor
Namita Gahtori
Copy Editor
Cenveo Publisher
Services
Indexer
Cenveo Publisher
Services
Proofreader
Cenveo Publisher
Services
Technical Reviewers
Cameron Banga
Joshua Jamison
Adam Porter
Editorial Assistant
Olivia Basegio
Cover Designer
Chuti Prastersith
Compositor
Cenveo Publisher
Services
Contents at a Glance
Introduction
Part I
1
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
The Basics of Android User Interfaces
Android UI and Material Design. . . . . . . . . . . . . . . . . . . . . . 5
11
12
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Contents
Introduction
................................................1
Audience for This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Organization of This Book . . . . . . . . . . . . . . . . . . . . . . . . . 1
How to Use This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
This Books Website . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Conventions Used in This Book . . . . . . . . . . . . . . . . . . . . . . 2
ContEntS
ContEntS
xi
xii
ContEntS
11
12
ContEntS
xiii
Preface
Android has evolved at an incredible speed, and keeping up with the changes is a difficult job
for any developer. While working to keep up with the latest features and API changes, it can be
easy to neglect the design changes Android is undergoing. When Google announced the Material Design guidelines, even designers who had long dismissed Androids visuals started paying
attention.
Its more important than ever for Android developers to understand the core aspects of design
and the Material Design guidelines go some of the way toward making that possible; however,
without years of background in design, it can be difficult to make sense of everything. This
book will guide you through the real-world process of design starting from an abstract idea
and sketches on paper and working all the way through animations, RenderScript, and custom
views. The idea is to touch on each of the core concepts and cover enough so that you can have
productive conversations with designers or even create everything yourself.
Design has many purposes, but two of the most important are usability and visual appeal. You
want brand-new users to be able to jump into your app and get started without any effort
because mobile users are more impatient than users of nearly any other platform. Users need
to know exactly what they can interact with, and they need to be able to do so in a hurry while
distracted. That also means you have to be mindful of what platform conventions are in order
to take advantage of learned behavior.
If you have picked up this book, I probably do not need to go on and on about how important
design is. You get it. You want to make the commitment of making beautiful apps that are a
pleasure to use.
This book will serve as a tutorial for the entire design and implementation process as well as
a handy reference that you can keep using again and again. You will understand how to talk
with designers and developers alike to make the best applications possible. You will be able to
make apps that are visually appealing while still easy to change when those last-minute design
requests inevitably come in.
Ultimately, designers and developers both want their apps to be amazing, and I am excited to
teach you how to make that happen.
Ian G. Clifton
acknowledgments
You would think that the second edition of a book would be easier than the first, but when
you find yourself rewriting 90 percent of it because both the technology and design trends
are changing so rapidly, it helps to have assistance. Executive Editor, Laura Lewin, once again
helped keep me on track even as I restructured the book and dove in depth in places I didnt
originally expect. Olivia Basegio, the Editorial Assistant, kept track of all the moving pieces,
including getting the Rough Cuts online so that interested readers could get a glimpse into the
book as it evolved. Songlin Qiu was the Development Editor again and took on the task of making sense of my late-night draft chapters. I am also extremely appreciative of the work done by
the technical reviewers, Adam Porter, Cameron Banga, and Joshua Jamison, whose feedback
was instrumental in the quality of this book.
IntroductIon
Audience for This Book
This book is intended primarily for Android developers who want to better understand user interfaces
(UI) in Android. To focus on the important topics of Android UI design, this book makes the assumption
that you already have a basic understanding of Android, so if you havent made a Hello, World Android
app or set up your computer for development, you should do so before reading this book (the Android
developer site is a good place to start: http://developer.android.com/training/basics/firstapp/index.html).
Most developers have limited or no design experience, so this book makes no assumptions that you
understand design. Whenever a design topic is important, such as choosing colors, this book will walk
you through the basics, so that you can feel confident making your own decisions and understand what
goes into those decisions.
IntroductIon
simple. In addition, illustrations will make even the most complex examples clear, and every
example will be practical.
note
Notes look like this and are short asides intended to supplement the material in
the book with other information you may find useful.
tip
Tips look like this and give you advice on specific topics.
warning
Warnings look like this and are
meant to bring to your attention to potential issues you may run into or things you
should look out for.
Potential Data loss or security issues
Chap te r 10
Using AdvAnced
TechniqUes
264
Chapter 10
Identifying Jank
Unfortunately, development is never as easy as write it once and everything is perfect. In
addition to typical bugs that cause the app to crash or misbehave, youre also going to have
performance issues to figure out. When you scroll a view and it seems to stutter or hiccup,
dropping frames, the experience is bad. These hiccups are sometimes called jank, which is the
opposite of smoothness. You want your app to be as fluid as possible, so eliminating jank can
significantly improve the feel of your app.
In many cases, you will see jank but not know what is causing it. For instance, the
implementation of the custom view which blurs a portion of an image in the woodworking
tools app might be smooth on one device and not smooth on another, causing jank each time
a new set of tool images comes into view. Whats going on here? If you have difficulty seeing
jank, an easy way to help visualize it is by going into the developer options of your phone
and turning on Profile GPU rendering (the past few versions of Android have the On screen
as bars choice so that you dont have to grab the output from adb). Go back to the app and
scroll around for a bit. A graph of the rendering time will be displayed on top of the UI. The
X-axis represents rendering over time and the Y-axis represents the amount of time taken for a
frame. The horizontal green line is the limit (16 milliseconds); anything above that line means
something is taking too long and causing jank. Figure 10.1 shows an example.
You should notice that there are multiple graphs on the screen; one for each window. One
represents the status bar, one represents the navigation bar, and one represents the visible
application. Some devices will show the navigation bar and application graph on top of each
other, like in Figure 10.1, but you can discern between them by interacting with the app and
watching the graph draw itself. The bars are also made of three colors. The purple at the base
is used to indicate the draw time; this is the process of converting your draw commands into
whats called a display list. A display list is a group of OpenGL commands that have been
compiled for execution. Once thats done, the renderer has to execute the display list by
communicating with the GPU, represented by the red. At the top of each line is an orange cap.
Typically, that cap is small because it represents the amount of time the CPU is waiting for the
GPU to acknowledge the commands, which is nearly always fast if youre not doing any custom
GPU work.
265
266
Chapter 10
Systrace works by tracking the starting and stopping points of events. The events are identified
by strings called tags. Android has several built in that are enabled by default as well as some
advanced ones that are typically off. For now, leave the commonly used tags all enabled and
turn on RenderScript in the advanced options below (remember, we used RenderScript to blur
the portion of the image behind the text).
When you click OK, youll see a dialog informing you that it is collecting trace information.
Sometimes it can help to wait briefly (12 seconds) before interacting and then start interacting
with the app to reproduce the jank. The wait lets you create a baseline for how long events take
when there is no interaction, but its up to you whether thats useful. Once the time is up, the
data is pulled off the device and the HTML file is generated (Systrace currently doesnt tell you
that everything is ready; the dialog just goes away and the file appears where you specified).
Open it in your browser and prepare to be confused. You should see something like Figure 10.4
in your browser.
The HTML will display as a bunch of colorful lines and boxes that make no sense at first. The
display shows time along the X-axis and various events along the Y-axis. The wider a box is,
the longer it took to perform that operation. At the top will be the CPU info, if you had that
enabled. Then youll have various info, much of which wont be useful to you right now. Further
down, you will see surfaceflinger. SurfaceFlinger takes buffers of pixel data, composites them,
and then pushes them to the display. Big gaps in the SurfaceFlinger section when the UI should
have been changing (such as while scrolling) are generally problems, but we can scroll down
more to the app (the name should be on the left, though it is often cut off for longer names) for
more detail.
The controls for the Systrace HTML page are not particularly user friendly. Pretend your Systrace
output is as exciting as a first-person shooter and put your fingers on the W, A, S, and D keys.
The W and S keys zoom in and out, respectively, while the A and D keys pan. You can also click
and drag the mouse up or down to zoom. Double-clicking the mouse creates a guideline under
the mouse that you can then position by clicking where you want it. Once youve placed more
two guidelines or more, you can see the time between them at the top. At time of writing, the
documentation for Systrace is outdated, so the best source for learning the bizarre controls is
by clicking the question mark at the very top right when viewing a Systrace file.
Scroll down to the woodworking tools app (it should be the largest section) as shown in Figure
10.5. If you see several huge sections such as obtainView that report they never finished, then
Systrace is lying to you. The way the tool works is very simple. Each time a developer wants to
267
268
Chapter 10
track something (including the events that are tracked inside of Android itself), the developer
uses the Trace class (made available to application developers in Android 4.3; you can also
use TraceCompat from the support library), calling beginSection. When you begin a new
section, you give it a name, which shows up in the colored bars here. When that event you were
tracking is done, you call endSection. Simple, right? The problem is that ending a section
always ends the most recently started section. This means that if you forget to call endSection
such as when you bail out of a method early due to an exception, your section will not
end at the right time, if at all. There are a few places where this can happen in the Android
system code, unfortunately, so you can receive Systrace output that tells you something like
obtainView did not finish when you know it did (the view appeared on the screen).
Fortunately, you can fix the output of Systrace yourself by calling endSection where it was
missing. If you see this bug, then after each call to the static createFromBitmap method
of Allocation, call TraceCompats endSection method. This fixes the missing calls in
Allocation (a bug fix has been accepted for this in the Android source code itself, but it
hasnt yet made it into a major release) and now you can run Systrace again. Scrolling down
to the woodworking tools app, you should now see only a few rows with most of the entries
significantly smaller than they were. The areas where each tracked section is just a sliver are
generally good (remember, the X-axis is time) and the larger ones are generally bad. If you use
W on your keyboard (or click and drag up), you can zoom in on one of those bigger sections.
Double-clicking with the mouse will begin the placement of a timing guideline that you can
then position by moving the mouse and place by clicking. Creating two of these will tell you
the time between them. Figure 10.6 shows that one of the obtainView sections took
155 milliseconds, which is more than eight frames! Keep in mind the power of the device youre
testing on as well. In this case, the test was on a Nexus 5. A Nexus 6 might not drop as many
frames (a quick test shows it closer to 90 milliseconds), but the Nexus 5 is still in the middle
range of Android devices (especially when you look at markets across the world).
The obtainView section weve been looking at comes from AbsListViews package-private
method of the same name. Because we can be reasonably sure that the Android system code
around this is fast, the problem is within the getView method of our ToolGridAdapter. In
the Systrace output, we can also see that the image for the view is being decoded and that
alone is taking almost four frames; looking closer, you can see the image is being decoded
twice! Just fixing this issue will cut the total obtainView time almost in half.
Within the getView method, we call the setImageResource method of our
CaptionedImageView. That method simply sets the reference to our drawable and sets
the drawable for the image view and then moves on to the blur code. But look a little
closer. The drawable reference is being created by inflating the drawable via our resources.
The ImageView is then having its image set via the resource ID, which causes it to be
inflated again. By simply changing that line to instead call setImageDrawable and pass in
mDrawable, we eliminate that second instance of decodeBitmap, which was taking around
60 milliseconds.
Maybe you caught this back in Chapter 8, Applying the Design, but this is the type of mistake
thats very easy to make and yet might not be caught. Having a code review process helps
increase the chance that this will be caught, but there are still times when it will slip by or
you might be working on your own without anyone to review your code. By making use of
Androids performance tracking tools, you can catch issues like this, and you will eventually
start to get used to keeping your eyes out for these types of problems.
You can run the app with the change and immediately feel the difference, but its still not
smooth, so lets make better use of Systrace. We are reasonably sure that the slowdown is in
this area, so lets update the setImageResource method so that the first line beings a new
trace section and that section is ended in the last line of the method. You can call the sections
anything you want, but you can consider a prefix if youre adding a lot of related sections, so
269
270
Chapter 10
something like BLUR setImageResource tells you that this section is part of the overall
blurring process and is specifically the setImageResource call. Diving into the updateBlur
method, there are a lot of different places that might be the cause of slowdown. This is a
case where intuition and experience will help you decide, but you cant go wrong with extra
logging.
Anywhere that you create or manipulate a bitmap is a good place to track. For instance, the
two lines that create the portionToBlur and blurredBitmap objects can be wrapped with
TraceCompat calls (that is, put a call to beginSection before those objects are created and
a call to endSection after). Wrapping the full RenderScript section is also a good idea. You
can even add some sections within the RenderScript portion of the code to better understand
what is taking time there. Listing 10.1 shows an example of the setImageResource and
updateBlur methods.
Listing 10.1 An example of Methods with systrace Logging Added
public void setImageResource(@DrawableRes int drawableResourceId) {
TraceCompat.beginSection(BLUR setImageResource);
mDrawable = getResources().getDrawable(drawableResourceId);
mImageView.setImageDrawable(mDrawable);
updateBlur();
TraceCompat.endSection();
}
private void updateBlur() {
if (!(mDrawable instanceof BitmapDrawable)) {
return;
}
final int textViewHeight = mTextView.getHeight();
if (textViewHeight == 0) {
return;
}
// Determine the size of the TextView compared to the height of the
ImageView
final float ratio = (float) textViewHeight / mImageView.getHeight();
// Get the Bitmap
final BitmapDrawable bitmapDrawable = (BitmapDrawable) mDrawable;
final Bitmap originalBitmap = bitmapDrawable.getBitmap();
// Calculate the height as a ratio of the Bitmap
int height = (int) (ratio * originalBitmap.getHeight());
// The y position is the number of pixels height represents from
the bottom of the Bitmap
final int y = originalBitmap.getHeight() height;
TraceCompat.beginSection(BLUR createBitmaps);
final Bitmap portionToBlur = Bitmap.createBitmap(originalBitmap, 0,
y, originalBitmap.getWidth(), height);
final Bitmap blurredBitmap = portionToBlur.copy(Bitmap.
Config.ARGB_8888, true);
TraceCompat.endSection();
// Use RenderScript to blur the pixels
TraceCompat.beginSection(BLUR RenderScript);
RenderScript rs = RenderScript.create(getContext());
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs,
Element.U8_4(rs));
TraceCompat.beginSection(BLUR RenderScript Allocation);
Allocation tmpIn = Allocation.createFromBitmap(rs, portionToBlur);
// Fix internal trace that isnt ended
TraceCompat.endSection();
Allocation tmpOut = Allocation.createFromBitmap(rs,
blurredBitmap);
// Fix internal trace that isnt ended
TraceCompat.endSection();
TraceCompat.endSection();
theIntrinsic.setRadius(25f);
theIntrinsic.setInput(tmpIn);
TraceCompat.beginSection(BLUR RenderScript forEach);
theIntrinsic.forEach(tmpOut);
TraceCompat.endSection();
TraceCompat.beginSection(BLUR RenderScript copyTo);
tmpOut.copyTo(blurredBitmap);
TraceCompat.endSection();
new Canvas(blurredBitmap).drawColor(mScrimColor);
TraceCompat.endSection();
// Create the new bitmap using the old plus the blurred portion and
display it
TraceCompat.beginSection(BLUR Finalize image);
final Bitmap newBitmap = originalBitmap.copy(Bitmap.
Config.ARGB_8888, true);
final Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(blurredBitmap, 0, y, new Paint());
mImageView.setImageBitmap(newBitmap);
TraceCompat.endSection();
}
Running the app and using Systrace again, we can see that a particular instance of the
obtainView call is now taking 90 milliseconds with the decodeBitmap portion roughly twothirds of that. The RenderScript portion of our code is the majority of the rest of the time with
almost half of the RenderScript time coming from the copyTo call. Lets start with the image
loading portion, because thats the larger part.
271
272
Chapter 10
Optimizing Images
There are a few big things you can do to speed up your use of images. First, you can shrink the
image file sizes by stripping out metadata and adjusting the compression. Second, you can
size them correctly (loading an image thats bigger than it is displayed is obviously slower than
loading one thats exactly the size that will be displayed). Finally, you can keep them in memory
to avoid loading them again.
Shrinking Images
Many people arent aware that images can contain a lot more data than they need. For instance,
JPEGs can be progressive, which means they actually store multiple versions of the image at
progressively higher levels of detail. This was particularly helpful for old webpages on dialup,
when you wanted some sense of what the image was before all of it could be downloaded on
the slow connection, but it causes the images to be much larger and Android doesnt use this
extra data because the full image is already on the local disk. JPEGs can also store metadata in
EXIF or XMP formats. These are two different formats for storing information about the photo
such as when it was taken, what camera was used, and even how long the photo was exposed.
That data is great for photographers but it adds bulk to the image that isnt helpful for our app,
so it can be stripped out. Another common inclusion in JPEGs is actually a thumbnail of the
image. This is intended to help file browsers and cameras themselves to display a thumbnail
without having to read in massive images and scale them; it can be stripped out as well.
You can also adjust the compression of the image. Although a more compressed image will still
take up the same amount of memory once it is decompressed and decoded, it can significantly
decrease the loading time because the amount of data read from disk can be substantially
decreased. JPEG is a lossy format, which means you lose image detail by compressing it, but
you can decrease file sizes substantially with only minor changes in compression. Typically,
the compression level is described in terms of quality where 100 is highest quality and least
compression. Although you might want to keep quality closer to 100 for your own personal
photos, that isnt necessary for most app images like what are in the woodworking tools app.
The amount of compression you can use while maintaining quality will vary depending on what
is in the image (e.g., details like thin letters will look poor faster than something like a tree in the
background), but you can generally start at a quality level of 90 and see how it looks.
By stripping out all this extra data and changing the quality level to 90, we decrease the hero
image sizes in the woodworking tools app substantially. For instance, the image of the clamps
was 493KB and it is now 272KB. The smallest image (in terms of file size) was the drill at 165KB
and even it shrank down to 64KB. Testing the app again shows that the time to decode the
images has gone from about 60 milliseconds to about half that (with a fair bit of variation).
Photoshop makes this pretty easy by picking Save for Web and ensuring that the quality is set
how you want, it is not progressive, and no metadata is enabled. The process in GIMP is slightly
different, starting with the Export As command that will give you an Export Image as JPEG
opTiMizing iMAges
dialog when saving as a JPEG; the dialog has Advanced Options where you want to make
sure the image is not progressive, does not contain EXIF or XMP data, and does not have an
embedded thumbnail.
Although these images are JPEGs, the same idea of shrinking down the file size applies to PNGs.
PNGs are lossless, so you should always use the maximum compression. PNGs can be 8-bit
(256 colors), 24-bit (red, green, and blue channels of 256 values each), or 32-bit (adding the
alpha channel with 256 values). You can also save them with custom palettes, which can
significantly shrink down the overall size. Many graphics programs support shrinking PNGs
quite a bit themselves, so look for those options (such as a save for web feature). There are
also third-party tools like pngcrush, which will try many different ways of compressing and
shrinking the image to give you a smaller file size.
273
274
Chapter 10
referencing, so it is slow (defeating the purpose of optimizing this code in the first place). You
should typically avoid using that method.
Listing 10.2
A BitmapUtils class
opTiMizing iMAges
case R.drawable.hero_image_drill_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_drill_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_drill_468;
}
break;
case R.drawable.hero_image_sander_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_sander_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_sander_468;
}
break;
case R.drawable.hero_image_router_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_router_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_router_468;
}
break;
case R.drawable.hero_image_lathe_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_lathe_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_lathe_468;
}
break;
case R.drawable.hero_image_more_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_more_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_more_468;
}
break;
}
return resourceId;
}
}
Testing out loading images that are the correct size for a Nexus 5 shows that we drop from the
30 milliseconds we saw after shrinking the file sizes in the previous section to just 7 milliseconds!
This has also made our blurring code significantly faster (down from 30 milliseconds to about
15 milliseconds) because its operating on fewer pixels. Overall, it is still taking about 22 milliseconds
to get the view, so its still slow, but the improvements so far have been substantial.
275
276
Chapter 10
Before we move on, its worth noting that you can also tackle this by loading the images at a
smaller size using the BitmapFactory class, which supports subsampling. By subsampling,
you can read a fraction of the number of pixels. For instance, if you have an image that was
1000px wide but you only need it at 500px wide, you can read every other pixel. This isnt as
efficient as providing correctly sized images, but it is more universal.
The general idea is that you read in just the metadata about the image (which includes the
dimensions) by making use of the Options class. Create a new instance of the Options
class and set inJustDecodeBounds to true. Now when you decode the image with
decodeResources, you use the Options object to tell it that you only want the bounds
(the size of the image). The Options object will now have its outWidth, outHeight, and
outMimeType set to the values of the actual image (and BitmapFactory will return null).
Once you know how big the image is, you figure out how to subsample the image. The
BitmapFactory class works in powers of 2, so you can subsample every second pixel, every
fourth pixel, every eighth pixel, and so forth. Using a simple while loop, we can double the
sample size until the resulting image will be just larger than the desired width. Listing 10.3
shows a simple implementation of this method.
Listing 10.3 The getSizedBitmap Method
public static Bitmap getSizedBitmap(@NonNull Resources res,
@DrawableRes int resId, int desiredWidth) {
// Load just the size of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Options now has the bounds; prepare it for getting the actual
image
options.inSampleSize = 1;
options.inJustDecodeBounds = false;
if (options.outWidth > desiredWidth) {
final int halfWidth = options.outWidth / 2;
while (halfWidth / options.inSampleSize > desiredWidth) {
options.inSampleSize *= 2;
}
}
return BitmapFactory.decodeResource(res, resId, options);
}
This is a simple way of making your image loading more efficient and this technique can be used
throughout your app; however, it isnt as efficient as having your images exactly the correct size.
opTiMizing iMAges
Testing image loading with this method, the average speed is around 15 milliseconds (with a fair
bit of variation), compared to the 30 milliseconds without this method or the 7 milliseconds with
properly sized images.
277
278
Chapter 10
/**
* Returns the size of the cache in kilobytes
*
* @return int total kilobytes to make the cache
*/
private static int getCacheSize() {
// Maximum KB available to the VM
final int maxMemory = (int) (Runtime.getRuntime().maxMemory()
/ 1024);
// The smaller of an eighth of the total memory or 16MB
final int cacheSize = Math.min(maxMemory / 8, MAXIMUM_SIZE_IN_KB);
Log.v(TAG, BitmapCache size: + cacheSize + kb);
return cacheSize;
}
}
We can create the BitmapCache in our BitmapUtils class and then add some simple
methods for interacting with it. In the case of our grid of images, we actually care more about
the versions of the images that have been blurred along the bottom already, so we can directly
cache those. Listing 10.5 shows the BitmapUtils methods weve added and Listing 10.6
shows the updated methods in CaptionedImageView.
Listing 10.5 The BitmapUtils class Updated to Use the cache
publicclass BitmapUtils {
private static final int THUMBNAIL_SIZE_336 = 336;
private static final int THUMBNAIL_SIZE_468 = 468;
private static final BitmapCache BITMAP_CACHE = new BitmapCache();
public synchronized static void cacheBitmap(@NonNull String key,
@NonNull Bitmap bitmap) {
BITMAP_CACHE.put(key, bitmap);
}
public synchronized static Bitmap getBitmap(@NonNull String key) {
return BITMAP_CACHE.get(key);
}
public synchronized static Bitmap getBitmap(@NonNull Resources res,
@DrawableRes int resId) {
String key = String.valueOf(resId);
Bitmap bitmap = BITMAP_CACHE.get(key);
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(res, resId);
BITMAP_CACHE.put(key, bitmap);
opTiMizing iMAges
}
return bitmap;
}
public static int getScreenWidth(@NonNull Context context) {
WindowManager windowManager = (WindowManager) context.
getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return point.x;
}
/**
* Returns a resource ID to a smaller version of the drawable, when
possible.
*
* This is intended just for the hero images. If a smaller size of
the resource ID cannot
* be found, the original resource ID is returned.
*
* @param resourceId int drawable resource ID to look for
* @param desiredSize int desired size in pixels of the drawable
* @return int drawable resource ID to use
*/
@DrawableRes
public static int getPresizedImage(@DrawableRes int resourceId, int
desiredSize) {
switch (resourceId) {
case R.drawable.hero_image_clamps_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_clamps_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468) {
return R.drawable.hero_image_clamps_468;
}
break;
case R.drawable.hero_image_saw_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_saw_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468) {
return R.drawable.hero_image_saw_468;
}
break;
case R.drawable.hero_image_drill_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_drill_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468) {
return R.drawable.hero_image_drill_468;
}
279
280
Chapter 10
break;
case R.drawable.hero_image_sander_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_sander_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_sander_468;
}
break;
case R.drawable.hero_image_router_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_router_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_router_468;
}
break;
case R.drawable.hero_image_lathe_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_lathe_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_lathe_468;
}
break;
case R.drawable.hero_image_more_1080:
if (desiredSize <= THUMBNAIL_SIZE_336) {
return R.drawable.hero_image_more_336;
} else if (desiredSize <= THUMBNAIL_SIZE_468)
return R.drawable.hero_image_more_468;
}
break;
}
return resourceId;
}
public static Bitmap getSizedBitmap(@NonNull Resources res,
@DrawableRes int resId, int desiredWidth) {
// Load just the size of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Options now has the bounds; prepare it for getting the
actual image
options.inSampleSize = 1;
options.inJustDecodeBounds = false;
if (options.outWidth > desiredWidth) {
final int halfWidth = options.outWidth / 2;
while (halfWidth / options.inSampleSize > desiredWidth) {
opTiMizing iMAges
options.inSampleSize *= 2;
}
}
return BitmapFactory.decodeResource(res, resId, options);
}
}
Listing 10.6
281
282
Chapter 10
Given that on a typical device six of the seven images in the woodworking tools app are
available on the first screen (once the spacing is back to normal); you might consider precaching the seventh image. By precaching them all, you will slightly increase the loading
time of the app, but you will ensure that the scrolling is smooth. If you had even more images
to handle, you might even move the image loading and blurring to a background thread.
Although RenderScript is extremely fast, it still takes time pass the data to the GPU, process
it, and pass that data back, so its not a bad idea to push that work to a background thread if
youre going to be doing it often.
283
284
Chapter 10
In general, you dont want to allocate or release memory in any method that is already
potentially slow or gets called many times in succession. For instance, be careful in the
onDraw and onLayout methods of View (both are covered in Chapter 13, Developing Fully
Custom Views), getView of Adapter implementations, and any methods you trigger during
animations. If you have to allocate objects, consider whether its possible to keep them around
or reuse them (such as in an object pool).
Listing 10.7
Each getView call traverses the view to find the views that need to be updated. In this case,
there are four separate findViewById calls. Each call will first check the convertView
ID, then the children one at a time until a match is found. If this example has just the
convertView plus the four views that are searched for, the first call will check two views to
get the match, the next three, and so on. This leads to 14 view lookups in this simple case! The
more complex the view, the longer it takes to traverse the hierarchy and find the views you are
looking for.
The ideal solution would be to only have to find the views one time and then just retain the
references, and thats what the view holder pattern does. Because you are reusing views (via
the convert view), you have to traverse a finite number of views before you have found every
view you care about in the list. By creating a class called ViewHolder that has references to
each of the views you care about, you can instantiate that class once per view in the ListView
and then reuse that class as much as needed. This class is implemented as a static inner class, so
it is really just acting as a container for view references. See Listing 10.8 for a simple example of
a class that takes the view and sets all the necessary references.
Listing 10.8 An example of a ViewHolder class
private static class
/*package*/final
/*package*/final
/*package*/final
/*package*/final
ViewHolder {
ImageView imageView;
TextView count;
TextView title;
TextView subtitle;
/*package*/ ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.imageView);
count = (TextView) v.findViewById(R.id.count);
title = (TextView) v.findViewById(R.id.title);
subtitle = (TextView) v.findViewById(R.id.subtitle);
}
}
Looking back at the getView method, a few minor changes can significantly improve the
efficiency. If convertView is null, inflate a new view as we already have and then create a
new ViewHolder instance, passing in the view we just created. To keep the ViewHolder
with this view, we call the setTag method, which allows us to associate an arbitrary object
with any view. If convertView is not null, we simply call getTag and cast the result to the
ViewHolder.
Now that we have the ViewHolder, we can just reference the views directly, so the rest of the
getView code is not only much simpler than before but also better performing and easier to
read. See Listing 10.9 for the updated getView call. Any time you use an adapter and you use
the child views in the getView method, you should use this view holder pattern. For example,
the ToolArrayAdapter in the woodworking tools app should be updated to use the view
holder pattern; give it a try.
285
286
Chapter 10
Eliminating Overdraw
Overdraw is when your app causes pixels to be drawn on top of each other. For example,
imagine a typical app with a background, whether plain or an image. Now you put an
opaque button on it. First, the device draws the background; then it draws the button. The
background under the button was drawn but is never seen, so that processing and data
transfer are wasted.
You might wonder how you can actually eliminate overdraw then, and the answer is that
you do not need to. You only need to eliminate excessive overdraw. What excessive
means is different for each device, but the general rule of thumb is that you should not be
drawing more than three times the number of pixels on the screen (as detailed in Chapter 7,
Designing the Visuals). When you go above three times the number of pixels, performance
often suffers.
Its worth noting that some devices are better than others at efficiently avoiding drawing pixels
when opaque pixels would be drawn right on top of them. GPUs that use deferred rendering
are able to eliminate overdraw in cases where fully opaque pixels are drawn on fully opaque
pixels, but not all Android devices have GPUs that use deferred rendering. Further, if pixels have
any amount of transparency, that overdraw cannot be eliminated because the pixels have to be
combined. That is why designs that contain a significant amount of transparency are inherently
more difficult to make smooth and efficient than designs that do not.
Overdraw is easiest to eliminate when you can see it. Android 4.2 and newer offer a developer
option to show GPU overdraw by coloring the screen differently based on how many times a
pixel has been drawn and redrawn. To enable it, go to the device settings and then Developer
options and scroll to the drawing section to enable the Show GPU Overdraw option (see
Figure 10.7). When this option is checked, apps will be colored to show the amount of overdraw.
Current versions of Android dont require restarting the app, but older versions do.
First, you should understand what the color tints mean. If there is no tint, there is no overdraw,
and this is the ideal situation. A blue tint indicates a single overdraw (meaning the pixel was
drawn once and then drawn again), and you can think of it as being cold because your
device can easily handle a single level of overdraw (so the processor is not overheating). When
something is tinted green, it has been overdrawn twice. Light red indicates an overdraw of
three times, and dark red indicates an overdraw of four (or more) times (red, hot, bad!).
Large sections of blue are acceptable as long as the whole app is not blue (if it were, thatd
suggest youre drawing the full screen and immediately redrawing it, which is very wasteful).
Medium-sized sections of green are okay, but you should avoid having more than half of the
screen green. Light red is much worse, but its still okay for small areas such as text or a tiny
icon. Dark red should make you cry. Well, maybe not cry, but you should definitely fix any dark
red. These areas are drawn five times (or more), so just imagine your single device powering five
full screens and you should realize how bad this is.
287
288
Chapter 10
Figure 10.8 shows a very simple design that is just a list of text. Judging by the simple
appearance, it looks like the device has to do minimal work to get these pixels on the display;
however, we can turn on the overdraw visualization and see how bad things actually are. Figure
10.9 shows the design tinted by the Show GPU Overdraw option. The full source code for this
example is in the OverdrawExample project in the chapter10 folder.
hierArchy viewer
First, you should know that the theme your app uses should have a window background. This
can be a drawable and it is usually a simple color. Android uses this when your app is first being
displayed to immediately show some visual indication of what your app should look like even
before the views have been inflated. This makes the device feel more responsive because it can
respond to the tap even before youve initiated the activity and inflated its views. This window
background stays on the screen and everything else is painted on top. That means if you have
an activity with a layout that also draws a background, you can very easily draw all pixels on the
screen twice and then more times when the views are put on top.
Another common source of overdraw is with items in a ListView. The example is not
only drawing a white background with the activitys base view right on top of the window
background, it is drawing a white background for each list item over that, which is entirely
unnecessary. By simply eliminating the extra backgrounds, the overdraw visualization (shown
in Figure 10.10) is immediately improved.
Remember that you dont need to eliminate all overdraw, but you should generally minimize
it. You should be conscious of what views are drawing in front of and check the overdraw
visualization now and then.
Hierarchy Viewer
Hierarchy Viewer is the unsung hero of layout optimization. It hasnt seen a whole lot of change
since the early versions, but it still remains a great go-to tool for figuring out what is happening
with your layouts. It can be used for simply figuring out why a view doesnt display or to figure
289
290
Chapter 10
out why a hierarchy is slow to load. It can even output your views as a PSD, allowing you to
inspect positioning and colors with precision that is hard to match from simple screenshots.
If your device is running Android 4.0 (or lower) and is unlocked, everything should just work.
If its running 4.0 (or lower) and it is locked, you can use the ViewServer class from Romain
Guy (https://github.com/romainguy/ViewServer) in your app (be sure to add the internet
permission). If your device is running Android 4.1 or newer, you need to set an environment
variable called ANDROID_HVPROTO with a value of ddm. In Windows, you can open My
Computer, Property, Advanced, Environment Variables, and click New to create it. For Mac youll
open .bash_profile in your home directory (note that the file starts with a dot, which means
it is hidden by default). Add a line that contains export ANDROID_HVPROTO=ddm and save the
file. Now type source ~/.bash_profile from the command line (this causes the file to be
re-read so that the variable is immediately set). For Linux, you can follow the same steps as for
Mac but the file is .bashrc in your home directory.
Open Android Device Monitor (under the Tools menu and the Android submenu). The Hierarchy
Viewer is a different perspective, so open the Window menu and click the Open Perspective
option. Select Hierarchy View and click OK. If you havent already connected your device and
opened the screen you want to inspect, do so now.
On the left side, you should see your device(s) listed. Select it and click the Load view
hierarchy button (thats the icon next to the refresh button; you can also click the downwardfacing triangle and select the option there). If the icon is grayed out, that typically means there
is an issue communicating with the device and more details should be available in the console
(usually on the bottom right). If youve already followed the directions from two paragraphs
ago and its still gray, you can also try closing out Android Studio (and anything else that
might be communicating with the device) and then run Android Device Monitor directly (run
monitor from the Android SDK tools directory).
Once the view hierarchy has loaded, the left window will show view properties, the center
of the screen will be the detailed view hierarchy, the top right will be an overview, and the
bottom right is the layout view that lets you see what portion of the screen the selected view is
responsible for (the bottom right may be showing the console tab, so just click the Layout View
tab). Your screen should look like Figure 10.11.
Each gray box in the tree view (the center window) represents a view. The boxes can have the
class type (e.g., LinearLayout), the memory address, the ID (e.g., id/content), performance
indicators, and a view index. The view index shows you the views position within the parent,
where the first child is position 0. The performance indicators are simply colored circles that
indicate the time it took to measure the view, the time it took for the layout pass, and the time
it took to draw the view. Newer versions of Hierarchy Viewer require you to click the icon with
the three circles to obtain the layout times. These indicators on the gray boxes are broken into
three groups. If a view is within the fastest 50% of views for the given indicator (e.g., draw time),
hierArchy viewer
Figure 10.11 After the view hierarchy has been loaded, this is what you should see
that view will be green for that circle. If its in the 50% of slow views, it will be yellow. If it is the
slowest of all the views, it is red. Its important to realize these are relative indicators, so a view
hierarchy that is extremely fast and efficient will still have a view with a red indicator for each
circle just as an extremely slow hierarchy will.
By clicking a gray box, you can see an image of the view, a count of how many views this view
represents (a 1 indicates the view itself; a 2 indicates the view plus a child view), and the exact
times for measuring, laying out, and drawing the view. In the view properties (the left window),
you can see virtually everything you could want to know about a view. This is extremely helpful
when troubleshooting.
291
292
Chapter 10
instead of below the previous view is usually enough to get the developer to realize the simple
mistake.
Exporting to PSD
One of the extremely powerful but often overlooked features of Hierarchy Viewer is the
ability to export a layout hierarchy as a Photoshop Document (a PSD file). This can be hugely
valuable to designers, so make sure they are aware of this functionality. There is a rather
forgettable-looking button above the tree view that appears to be three overlapping squares.
Thats the Capture Layers button. If you do not see it, you can also click the downward-facing
triangle to get the list of options and select it from there. The resulting PSD can take a while
to be generated, so be patient. If it fails, you will see an error in the console and can try again
(occasionally it helps to reconnect the hardware device or restart the emulator).
Because this PSD is not using any advanced features such as layer masks, you can actually open
it in GIMP and other tools as well. Along with the techniques discussed earlier in the chapter,
this is an excellent method of detecting overdraw.
Exporting to a PSD is a great way for a developer and a designer to speak the same language.
The designer can inspect in detail exactly what is going on with a layout by tweaking the layers
and then tell the developer which layer has an issue (the layers are named after the view IDs
when present, making it extra easy to associate a layer with a view). This also gives the designer
the opportunity to make changes to further optimize the design. Perhaps initially a view
seemed best at 50-percent opacity, but now the designer can tweak how opaque a view is just
like any layer in Photoshop and determine that 40% is actually better.
One thing to note is that the layers are all rasterized. In simplistic terms, the pixels that
each view creates are what are actually exported as layers. TextViews do not create actual
Photoshop text layers, for instance. That also means that if you have a complex view thats
cUsToM fonTs
drawing shapes, text, and images, only the resulting pixels are exported, so you cant see what
each layer of that view looks like.
Custom Fonts
There are times when using a custom font can improve your app. Some apps designed for
reading provide additional font choices for users; other apps might use fonts specific to their
brand. When deciding on whether to use an additional font, consider how it helps the user
experience. Dont include a font just because its popular or makes the app look different from
others; include a font because a usability study has shown that your app is easier to read with
the font or because your brand requires it and you want to avoid using images for custom text.
The Roboto font family was built specifically for Android and is the default font for Android
4.0 (Ice Cream Sandwich) and above. Whenever possible, it is the font you should use. You
can download the font from the Google design site (http://www.google.com/design/spec/
resources/roboto-noto-fonts.html), and it includes multiple variations. In addition to Roboto
regular, there is a thin version, light version, medium version, black version, and condensed
version (as well as bold and italic versions where applicable).
Because this font was built for Android specifically, it displays very well on a variety of densities
and screen types. Many of the most commonly used fonts today were designed for print, which is
a very different medium than an electronic display, so some of the fonts that look great on paper
do not reproduce as well onscreen. In particular, if you are considering light or thin fonts, be sure
to test them on medium- and high-density displays and test them against low-end devices with
AMOLEDs (most modern AMOLEDs are reasonably comparable to LCDs, even besting them in
some measures, but older and lower quality AMOLEDs like the ones used for the Nexus S have
a different subpixel arrangement than a traditional LCD and on top of that have a low enough
resolution that the subpixel arrangement can cause display issues for very thin items).
If you do decide to use an alternate font, you need to put it in a directory called assets within
the root directory of your project. The easiest way to use a custom font in your app is to extend
TextView to create your own class. Listing 10.10 shows an example.
Listing 10.10 A custom TextView for displaying a font
public class TextViewRobotoThin extends TextView {
/**
* This is the name of the font file within the assets folder
*/
private static final String FONT_LOCATION = roboto_thin.ttf;
private static Typeface sTypeface;
public TextViewRobotoThin(Context context) {
super(context);
293
294
Chapter 10
setTypeface(getTypeface(context));
}
public TextViewRobotoThin(Context context, AttributeSet attrs) {
super(context, attrs);
setTypeface(getTypeface(context));
}
public TextViewRobotoThin(Context context, AttributeSet attrs, int
defStyleAttr) {
super(context, attrs, defStyleAttr);
setTypeface(getTypeface(context));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TextViewRobotoThin(Context context, AttributeSet attrs, int
defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setTypeface(getTypeface(context));
}
/**
* Returns the Typeface for Roboto Thin
*
* @param context Context to access the apps assets
* @return Typeface for Roboto Thin
*/
public static Typeface getTypeface(Context context) {
if (sTypeface == null) {
sTypeface = Typeface.createFromAsset(context.getAssets(),
FONT_LOCATION);
}
returnsTypeface;
}
}
At the top of the class is a static string specifying the name of the font file. Each of the normal
constructors calls setTypeface. A public static method called getTypeface() will create
the Typeface from the font file in the assets directory, if it hasnt already been created, and
then return the Typeface. This is useful for times when you might access the Typeface for
other uses (perhaps you do some custom drawing using this Typeface elsewhere). By having
this public static method, anywhere in your code that needs this custom Typeface has one
place to go, and you can just change the FONT_LOCATION if you need to change the font
everywhere in the app.
You can now use this class anywhere you would use an ordinary TextView. For instance, you
can replace the default hello world TextView with this in a new project. Figure 10.12 shows
how this custom TextView looks on an actual device.
coMpLex TexTviews
Complex TextViews
TextView is an extremely powerful view in Android. Obviously, theyre able to display text,
but they can also display several styles of text, different fonts or colors, and even inline images,
all within a single TextView. You can have specific portions of text respond to click events
and really associate any object you want with any portion of text. These ranges of text are
generically referred to as spans, as in a span (range) of bold text or a span of subscript.
Existing Spans
Android has a large number of prebuilt spans you can take advantage of. Because you can assign
any object as a span, there isnt an actual span class. Thats great in that it gives you a huge
amount of flexibility, but it also means you have to dig a little to figure out what is supported.
First, you should know about the two main types of spans defined by the interfaces
CharacterStyle and ParagraphStyle. As you can probably guess, these interfaces refer to
spans that affect one or more characters and spans that affect entire paragraphs, respectively.
Most spans will implement one of these two interfaces (although many implement more than just
these). See the following list of built-in spans to get an idea about what is already supported:
AbsoluteSizeSpanA span that allows you to specify an exact size in pixels or density
independent pixels.
295
296
Chapter 10
BackgroundColorSpanA span that specifies a background color (the color behind the
ClickableSpanA span that has an onClick method that is triggered. (This class is
abstract, so you can extend it with a class that specifies the onClick behavior.)
spacing.
DynamicDrawableSpanA span that you can extend to provide a Drawable that may
EasyEditSpanA span that just marks some text so that the TextView can easily
delete it.
ForegroundColorSpanA span that changes the color of the text (basically just called
setColor(int) on the TextPaint object).
IconMarginSpanA span that draws a Bitmap plus the specified amount of spacing.
ImageSpanA span that draws an image specified as a Bitmap, Drawable, URI, or
resource ID.
LocaleSpanA span that changes the locale of text (available in API level 17 and above).
MaskFilterSpanA span that sets the MaskFilter of the TextPaint (such as for
blurring or embossing).
MetricAffectingSpanA span that affects the height and/or width of characters (this
is an abstract class).
QuoteSpanA span that puts a vertical line to the left of the selected text to indicate it is
RasterizerSpanA span that sets the Rasterizer of the TextPaint (generally not
useful to you).
RelativeSizeSpanA span that changes the text size relative to the supplied float
(for instance, setting a 0.5 float will cause the text to render at half size).
ScaleXSpanA span that provides a multiplier to use when calling the TextPaints
setTextScaleX(float) method. (In other words, setting this to 0.5 will cause the text
SubscriptSpanA span that makes the text subscript (below the baseline).
coMpLex TexTviews
SuperscriptSpanA span that makes the text superscript (above the baseline).
TabStopSpan.StandardA span that allows you to specify an offset from the leading
margin of a line.
styling.
URLSpanA ClickableSpan that attempts to view the specified URL when clicked.
Another easy method for implementing spans is to use the Linkify class. The Linkify class
allows you to easily create links within text for web pages, phone numbers, email addresses,
physical addresses, and so on. You can even use it for custom regular expressions, if youre so
inclined.
Finally, you can also manually set spans on anything that implements the Spannable interface.
If you have an existing String or CharSequence that youd like to make Spannable,
use the SpannableString class. If you are building up some text, you can use the
SpannableStringBuilder, which works like a StringBuilder but can attach spans. To
the untrained eye, the app in Figure 10.13 is using two TextViews and an ImageView, but it
actually has just a single TextView. See Listing 10.12 to understand how you can do this with
one TextView and a few spans.
297
298
Chapter 10
recycLerview
RecyclerView
If youve been doing Android development for some time, youve probably come across
issues with ListView. For most uses ListView is great. It handles everything you need and
it is efficient; however, there are times when ListView doesnt do everything you want. For
instance, animating views within ListView has a lot of challenges and there isnt a good way
to change how the items are laid out.
To solve these issues, RecyclerView was created. Its name is a reference to the process of
view recycling that weve discussed previously where a view that goes off screen can then be
reused for a new view coming onto the screen. RecyclerView works similarly to ListView
but with a more modular architecture. For instance, instead of assuming that you want your
items vertically stacked, you supply a layout manager that handles determine how to lay out
the items. Given that RecyclerView can do everything that ListView can, you might be
wondering when you should still use ListView. The simple answer is to use ListView unless
you encounter one of its limitations. Contrary to some opinions, ListView isnt dead and you
shouldnt change all your ListViews over to RecyclerViews without reason. If you find that
ListView doesnt work for you, thats the time to switch over to RecyclerView.
If you want a good starting point for playing around with RecyclerView, check out the
sample. From Android Studio, open the File menu and select Import Sample and then
type Recycler View in the search box. This will let you quickly set up a project that uses
RecyclerView so that you can see how it works and experiment with it.
Layout Manager
To tell RecyclerView how to arrange the views, you need a layout manager. Its responsible for
measuring and positioning views as well as handling the view recycling policy. Fortunately, there
are some built in ones for the typical use cases. Youll commonly use LinearLayoutManager,
which can give you a ListView-like display but also supports horizontal arrangement. You may
also use GridLayoutManager or StaggeredGridLayoutManager for times when you want
grids of items rather than just rows or columns.
Adapter
Like ListView, RecyclerView uses an adapter to supply its views, but it works a little
differently (also note that its RecyclerView.Adapter rather than android.widget.
299
300
Chapter 10
Adapter). You commonly have to use the view holder pattern with adapters for ListView
as described earlier in the chapter to avoid repeated calls to findViewById, but that pattern
is built in to RecyclerView with an actual ViewHolder class. Rather than the getView
method, this adapter has two methods. First, onCreateViewHolder is expected to create
any views that are necessary, but it returns a new ViewHolder instance that references those
views. Second, onBindViewHolder is expected to set all the views up for a given position
using the ViewHolder instance.
Note that a key difference between AdapterView and RecyclerView is how you listen to
clicks. Rather than assigning a single onItemClickListener, RecyclerView just uses
the regular onClickListener and related classes. Typically any necessary listeners are
set in onCreateViewHolder and the position or object(s) they care about are updated in
onBindViewHolder.
Item Animator
Whenever the state of the RecyclerView changes, it needs to know how to animate
the change and thats where the ItemAnimator abstract class comes in. A concrete
implementation allows you to control the animations that are used to visualize these changes,
so that your users can easily understand what happened. By default, RecyclerView uses
the aptly named DefaultItemAnimator, but you can provide a custom implementation to
precisely control the behavior.
Item Decoration
RecyclerView has one more trick up its sleeve and thats the concept of item decoration,
which is based on the ItemDecoration abstract class. The idea is simple: sometimes you
need to draw more than just the views that are displaying your data. For instance, you might
draw dividers between items or visually group a section of items. ItemDecoration has both
onDraw and onDrawOver methods. The former draws before the views are drawn (such as
for backgrounds) and the latter draws after (meaning it draws in front of them). You can add
multiple ItemDecoration implementations to your RecyclerView to get the effect you
want, but you dont have to use any.
One additional feature ItemDecoration has is the ability to modify the position of views.
By overriding getItemOffsets, you can adjust positions as needed, which allows you to
manipulate the display in powerful ways such as visually clustering content based on proximity
or spacing.
Summary
In this chapter, you learned a wide variety of topics that help advanced developers make
even better apps. Using Systrace will allow you to get performance details that help you make
informed decisions on how you can improve your app and help you identify issues that are
sUMMAry
easily missed like decoding an image twice. You saw multiple techniques for improving the
efficiency of working with images from pre-sizing to background loading. Additional tools
and techniques for performance improvements followed before getting into advanced uses of
existing views by way of spans and the flexible RecyclerView.
In the next chapter, youll dive right into the world of drawing in Android. Youll learn how to
draw images and text as well as how to apply filters and compositing.
301
Index
A
abortAnimation(), 370
AbsListView class, 284
AbsoluteLayout, 62
AbsoluteSizeSpan, 295
AccelerateDecelerateInterpolator
class, 239
AccelerateInterpolator class, 239
accessible vocabulary, 182
action bar. see app bar
ActionBarCompat library, 70
activity transitions, 255259
Adapter class, 6061
AdapterViewAnimator, 62
AdapterView class, 57
interfaces for, 61
AdapterViewFlipper, 62
add, PorterDuff image compositing mode, 322
Adobe Illustrator, 118, 168169
AlignmentSpan.Standard, 295
alpha, View class attribute, 28
Amazon Appstore, 401
ambient light, 171
AnalogClock, 4546
Android Asset Studio, 390395
Android design website, 13
android:state_activated, 89
android:state_checkable, 89
android:state_checked, 89
android:state_enabled, 89
android:state_focused, 89
android:state_hovered, 90
android:state_pressed, 90
android:state_selected, 90
android:state_window_focused, 90
angle, ShapeDrawable class attribute, 94
AnimatedVectorDrawable class, 98100
animations, 104
form errors, 242246
icons, 246251
and Material Design, 1112
418
ATTRIBUTES
B
back button, 19
background, View class attribute, 28
BackgroundColorSpan, 296
backgrounds, 3940
Balsamiq, 119
bending to user, core principles, 19
better text drawable, 308310
Bitmap class, 311, 338339
BitmapShader, 325328
bottom, ShapeDrawable class attribute, 95
bottomLeftRadius, ShapeDrawable
class attribute, 94
bottomRightRadius, ShapeDrawable
class attribute, 94
BounceInterpolator class, 239
breaking comps into views, 200201
brightness, 173
Button class, 39
C
cache, images, 277283
CalendarView, 42
Camera app, 15
Canvas class, 305
capitalization, text, 180
CardView library, 7172
centerColor, ShapeDrawable class
attribute, 94
centerX, ShapeDrawable class
attribute, 94
centerY, ShapeDrawable class
attribute, 94
change log, Google Play, 389
CharSequence class, 236238
CheckBox, 42
CheckedTextView, 42
Chronometer, 46
circular reveal transitions, 259262
clear, PorterDuff image compositing mode, 316
ClickableSpan, 296
ClipDrawable class, 9293
CMYK (cyan, magenta, yellow, and black), 172
color, ShapeDrawable class attribute, 95
Color (Adobes tool), 177
color blindness, 177178
ColorMatrixColorFilter class, 314315
color (qualifier), 76
D
darken, PorterDuff image compositing mode,
320321
dashGap, ShapeDrawable class attribute, 95
419
420
E
EasyEditSpan, 296
EdgeEffect class, 351
EditText, 38, 404
eliminating, overdraw, 286289
ellipsize, TextView class attribute, 36
endColor, ShapeDrawable class attribute, 94
error cases, design, 184185
events, listening to, 4748
exit button, 19
ExpandableListView class, 59
external libraries, 114
extra, extra, extra high dots per inch (XXXHDPI),
32, 81, 198
extra, extra high dots per inch (XXHDPI), 32, 81
ExtractEditText, 46
extra high dots per inch (XHDPI), 32, 81
F
FAB, 23
FastOutLinearInInterpolator class,
239
FastOutSlowInInterpolator class, 240
feature graphic, Google Play, 397399
feedback, real user, 162164
filters, colors, 313325
flat design, 170
flowcharts, 114
focusable, View class attribute, 29
focused state, 17
fontFamily, TextView class attribute, 36
fonts
custom, 181182, 293295
Roboto font family, 293
TextView class, 293
ForegroundColorSpan, 296
FragmentBreadCrumbs, 62
fragments, 64
and activities, 130
lifecycle of, 6465
passing data to, 6566
problems associated with, 6970
prototypes, creation of. see prototypes,
creation of
tab, 142155
talking to activity from, 6669
transactions, 69
FrameLayout class, 52
full screen mode, 404405
G
Gallery app, 15
Gallery class, 60
garbage collection, controlling, 283284
GestureDetector class, 350
GestureOverlayView, 62
getBounds(), 304
getCurrVelocity(), 385
getIntrinsicHeight(), 304
getIntrinsicWidth(), 305
getOpacity(), 304
getScaledMinimumFlingVelocity(), 355
getScrollX(), 365
GIFs, 83
Gimp, 168
GLSurfaceView, 46
goals, 110111
device and configuration support, 113114
product, 112113
user, 111112
user personas, 112
Google Play, 387
application description, 388
application icon, 389395
change log, 389
feature graphic, 397399
promoting apps, 400401
promotional graphic, 399400
screenshots, 395397
video (YouTube), 400
Google Plus, 16
gradientRadius, ShapeDrawable class
attribute, 95
gradient shader, 325, 328330
kEyBoARD AvAIlABIlITy
graphical design
styles, 169170. see also specific styles
tools for, 168169
wireframes and, 168
graphics
feature graphic, Google Play, 397399
promotional. see promotional graphics
gravity
LinearLayout class attribute, 5253
TextView class attribute, 36
GridLayout, 63
GridLayout library, 72
GridView class, 59
H
hardware keyboard type, 80
HDPI (high dots per inch), 32, 81
height, ShapeDrawable class attribute, 95
Hierarchy Viewer, 289291
eliminating unnecessary views, 292
exporting Photoshop Document, 292293
missing views, finding, 291292
high dots per inch (HDPI), 32, 81
high-level flow, 114116
hint, TextView class attribute, 36
history, Android design, 6
home screen, 7
Honeycomb, 6, 233
full screen mode, 405
HorizontalIconView class, 352355
HorizontalScrollView class, 63
hot spot, 171
HSB (hue, saturation, and brightness), 172
vs. RGB, 173174
HTML class
spans, 297299
hue, 172
I
Ice Cream Sandwich, 6
IconMarginSpan, 296
icons
animations, 246251
design, 184
raster, animating, 250251
vector, animating, 246250
id, View class attribute, 29
IDs, 104105
Illustrator, 118, 168169
ImageButton class, 41
image files, 8384. see also raster images; vector
images
images
alternate sizes, generating, 198199
availability and size, 183
cache, 277283
display, 3941
nine-patch, 8486, 195198
optimization, 272283
right sizes for, 273277
round, shaders for, 325328
shrinking, 199, 272273
working with, 310313
XML drawables. see XML drawables
ImageSpan, 296
ImageSwitcher, 63
ImageView class, 4041
importantFor, View class attribute, 29
ink, as Material Design component, 1011
Inkscape, 118
innerRadius, ShapeDrawable class
attribute, 94
innerRadiusRatio, ShapeDrawable
class attribute, 94
InputMethodManager, dismissing software
keyboard, 404
inputType, TextView class attribute, 36
InsetDrawable class, 92
interaction, and Material Design, 1112
interpolators, 232233, 236
IntEvaluator class, 235
ItemAnimator class, 300
ItemDecoration class, 300
J
jank
identifications, 264265
Systrace and, 265271
Jelly Bean, 6
JPEGs, 83, 272273
K
kerning, 180
keyboard availability, 80
421
422
L
language, 77
language direction, 77
layer list, XML drawables, 8788
LayoutParams, RelativeLayout class,
5657
layout (qualifier), 76
layouts, 28
views, 333, 337338
LayoutTransition class, 252
LDPI (low dots per inch), 32, 81
leading, 180
LeadingMarginSpan.Standard, 296
leanback library, 73
left, ShapeDrawable class attribute, 95
level list, XML drawables, 91
LevelListDrawable class, 91
lifecycle, of fragments, 6465
lighten, PorterDuff image compositing mode, 320
lighting, 171
LightingColorFilter class, 313
LinearGradient, 325
LinearInterpolator class, 240
LinearLayout class, 5255
LinearLayoutManager class, 299
LinearOutSlowInInterpolator class, 240
lines, TextView class attribute, 37
line spacing, 180
lineSpacing , TextView class attribute, 37
listeners, 235
ListView class, 5859, 284, 299
LocaleSpan, 296
Lollipop, 7
long press gesture, 25
low dots per inch (LDPI), 32, 81
LruCache class, 277
LRU (least-recently-used) cache, 277
LTR (left-to-right) layout, 3234
M
MaskFilterSpan, 296
match_parent (layout parameter), 31, 55
DST_ATOP, 320
DST_IN, 318
DST_OUT, 318
DST_OVER, 318319
lighten, 320
multiply, 322323
overlay, 323
screen, 323
SRC, 316317
SRC_ATOP, 320
SRC_IN, 318
SRC_OUT, 318
SRC_OVER, 318319
XOR, 323325
MotionEvent.ACTION_CANCEL, 371
MotionEvent.ACTION_POINTER_UP, 371
MotionEvent.ACTION_UP, 370371
MotionEvent class, 350351, 369
MultiAutoCompleteTextView, 44
multiple devices, support for, 2324, 125126
multiply, PorterDuff image compositing mode,
322323
OnClickListener, 48
onCreate(Bundle), 64
onCreateView(LayoutInflater,
ViewGroup, Bundle), 64
onDestroy(), 65
onDestroyView(), 65
onDetach(), 65
OnDragListener, 48
onDraw(Canvas), 355
OnFocusChangeListener, 48
OnGenericMotionListener, 48
OnHoverListener, 48
onKeyDown(int, KeyEvent), 351
OnKeyListener, 48
onLevelChange(int), 305
OnLongClickListener, 48
onMeasure(int, int), 360
onOverScrolled(int, int, boolean,
boolean), 366
onPause(), 65
onResume(), 64
onScrollChanged(x, 0, oldX, 0),
365
onStart(), 64
onStateChange(int[]), 305
onStop(), 65
onTouchEvent(MotionEvent), 369, 371
OnTouchListener, 48
onViewStateRestored(Bundle), 64
optical bounds, 197198
optimization, images, 272283
orientation, 79
orientation, LinearLayout class, 54, 55
overdraw, eliminating, 286289
overlay, PorterDuff image compositing mode,
323
overScrollBy, 366, 370
OverScroller class, 351
OvershootInterpolator class, 240
423
424
Q
QuickContactBadge, 46
QuoteSpan, 296
R
RadialGradient, 325
RadioButton, 44
RadioGroup, 44
radius, ShapeDrawable class attribute, 94
raster icons, animating, 250251
raster images, 83
RasterizerSpan, 296
RatingBar, 44
raw (qualifier), 76
R class, 3031
resource qualifiers, 8081
R.drawable.header, 80, 81
RecyclerView.Adapter class, 299300
RecyclerView class, 299300
RecyclerView library, 73
region, 77
RelativeLayout class, 5556
RelativeSizeSpan, 296
rendering, deferred, 286287
ReplacementSpan, 296
resource qualifiers, 7681
list of, 7780
RGB (red, green, and blue)
vs. HSB, 173174
right, ShapeDrawable class attribute, 95
RippleDrawable class, 100101
Roboto, 12, 13
Roboto font family, 293
rounded corners, specifying, 95
round images, shaders for, 325328
RSSurfaceView, 47
RSTextureView, 47
RTL (right-to-left) layout, 3234
S
Samsung, 34
saturation, 172173
ScaleDrawable class, 93
scaleType attribute, values for, 4041
ScaleXSpan, 296
scene transitions, 252255
screen, PorterDuff image compositing mode,
323
screen aspect, 79
screens, keeping on, 405
screenshots, Google Play, 395397
TABWIDgET
screen size, 78
determining, 406407
Scroller class, 351
ScrollerCompat class, 351
ScrollView, 63
SearchView, 63
SeekBar, 44
setAlpha(int), 304
setColorFilter(ColorFilter), 304
setDrawables(ListDrawable), 356357
setWillNotDraw(false), 355
setWillNotDraw method, 334
shaders, 325330
gradient, 325, 328330
round images, 325328
shadowColor, TextView class attribute, 37
shadowDx, TextView class attribute, 37
shadowDy, TextView class attribute, 37
shadowRadius, TextView class attribute, 37
shadows
in Material Design, 910
text, 180181
shape, ShapeDrawable class attribute, 94
ShapeDrawable class, 9396
sharing, 1516
Show GPU Overdraw option, 287, 288
shrinking images, 199, 272273
simple text drawable, 306308
sizes, text, 180
Sketch tool, 118119
skeuomorphic design, 11
skeuomorphism, 169
slicing, 193
easy, 193194
generating alternate sizes, 198199
nine-patch images, 195198
SlidingDrawer, 63
smallest width, 78
software keyboard, dismissing, 404
Space, 47
spacing, text, 180
spans
for complex text, 297299
existing, 295297
Spinner, 44
Spinner class, 60
SRC, PorterDuff image compositing mode,
316317
T
TabHost, 63
TableLayout, 63
TableRow, 63
tabs, 2223, 132134
TabStopSpan.Standard, 297
TabWidget, 63
425
426
U
UCD (User-Centered Design), 108110
UI mode, 79
UI threads, 408409
UnderlineSpan, 297
up indicator, 125
URLSpan, 297
useLevel, ShapeDrawable class attribute,
94
User-Centered Design (UCD), 108110
user goals, 111112
user personas, 112
V
ValueAnimator class, 233234, 235
values (qualifier), 76
VectorDrawable class, 96
attributes for, 9798
vector icons, animating, 246250
vector images, 84
VideoView, 47
video (YouTube), 400
view animations, 232233
ViewAnimator, 63
View class, attributes. see attributes, View
class
ViewFlipper, 63
ViewGroup class, 52, 360
ViewHolder class, patterns, 284286
ViewPager class, 61
ViewPropertyAnimator class, 241242
views, 28
breaking comps into, 200201
ZoomcoNTRolS
W
WCAG (Web Content Accessibility Guidelines),
179
website, Android design, 13
WebView, 47
weight, LinearLayout class attribute, 53
width, ShapeDrawable class attribute, 95
wireframes, 117119
content pieces, 122123
detail pages, 123125
and graphical design, 168
naming conventions, 127
navigation, 119122
supporting multiple devices, 125126
Wireframe Sketcher, 119
woodworking app, 178
X
XHDPI (extra high dots per inch), 32, 81
XML drawables, 8687
AnimatedVectorDrawable class,
98100
ClipDrawable class, 9293
InsetDrawable class, 92
layer list, 8788
level list, 91
RippleDrawable class, 100101
ScaleDrawable class, 93
ShapeDrawable class, 9396
state list, 8891
tiles, 194
TransitionDrawable class, 9192
VectorDrawable class, 9698
xml (qualifier), 76
XOR, PorterDuff image compositing mode,
323325
XXHDPI (extra, extra high dots per inch), 32, 81
XXXHDPI (extra, extra, extra high dots per inch),
32, 81, 198
Z
ZoomButton, 47
ZoomControls, 63
427