Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 35  Material Design


Elevation and Z values


The most apparent way users will see the depth in your interface is by seeing how elements of your app
cast shadows on one another. Some might think that a perfect world would be one where the designers
worry about drawing those shadows and we developers go eat bagels. (Opinions differ on what a
perfect world looks like.)


But doing that with a variety of surfaces in play – while animating, no less – is not possible for
designers to do by themselves. Instead, you let Android take care of drawing the shadows by giving
each of your Views an elevation.


Lollipop introduced a z-axis to the layout system, allowing you to specify where a view lives in 3-D
space. Elevation is like the coordinates assigned to your view in layout: You can animate your view
away from this position, but this is where it naturally lives (Figure 35.4).


Figure 35.4  Elevation on the Z plane


To set the elevation value, you can either call the View.setElevation(float) method or set the value
in your layout file.


Listing 35.1  Setting elevation on a view in a layout file


<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="2dp"/>


Because this is intended to be your baseline Z value, using the XML attribute is preferred. It is also
easier to use than setElevation(float), because the elevation attribute is silently ignored on older
versions of Android, so you do not need to worry about compatibility.


To change a View’s elevation, you use the translationZ and Z properties. These work exactly like
translationX, translationY, X, and Y, which you saw in Chapter 32.


Z’s value is always elevation plus translationZ. If you assign a value to Z, it will do the math to
assign the right value to translationZ (Figure 35.5).


Figure 35.5  Z and translationZ

Free download pdf