One of the most important parts of any application's design and development is the graphical user interface (GUI) and screen layout design. Many of the most widely circulated Android applications are popular because of their visual design, animated graphics, and easy- or fun-to-use interfaces. We will explore the Java classes that provide the core foundation for all of these front-end capabilities in this chapter.
In Google Android, in order to interface with the smartphone screen, you use two core Java classes. These are two of the most important and often used classes in Android development:
The View
class
The ViewGroup
class
View
and ViewGroup
are core, high-level classes, created or subclassed from the Java Object
class, as are all Java classes. View
objects are created using the View
class. The View
class can also be used to create many lower-level, or more customized, Java classes. Those classes that are subclassed from the View
class inherit the characteristics of their superclass.
So, the basic screen layout in Android is controlled by a View
object, which contains a complex data structure that represents the content and layout parameters for a given rectangular section of the smartphone's display screen.
There may be one or more View
objects that make up the entire display screen, depending on how you use the View
and ViewGroup
classes to create the UI structure for your Android application's screen.
Each View
object controls and references its own rectangular view parameters, allowing you to control many attributes. Here are just some examples of the many attributes controlled by the View
class parameters available to programmers:
Bounds (measurements)
Layout on the screen
Order in which its layers are drawn
Scrolling
Focus
Keystroke interactions
Gesture interactions
Finally, View
s have the ability to receive events—interaction events between your application's end user and the View
object itself. For this reason, the View
class is the logical Java construct to subclass to build more detailed and specific UI elements, such as buttons, check boxes, radio buttons, and text fields.
The View
class serves as the foundation for UI elements that are subclasses of the View
class. Recall that in Java, a subclass is a more specific or detailed implementation of the class from which it is subclassed. For instance, the Button
class is subclassed from the TextView
class, which is subclassed from the View
class, which is subclassed from the Object
class. The Button
class is subclassed from the TextView
class because the Button
has a TextView
label and is thus a more specialized version of a TextView
; that is, it is a clickable TextView
with a button background appearance.
So many UI classes have been subclassed from the View
class that there is a name for them: widgets. All of these widgets are contained in a package (a collection of classes) called android.widget
. For example, you can access a Button
class via this package using android.widget.button
.
One of the most useful classes subclassed from the View
class is the ViewGroup
class. The ViewGroup
class is used to subclass layout container classes, which allow groups of View
objects to be logically grouped, arranged, and cascaded onto the screen.
ViewGroup
s are layout containers, usually collections of UI elements. In the diagram in Figure 6-1, View
could mean a button, a text field, a check box, and so on. This applies to any other type of UI element.
The remainder of this chapter explores the different types of ViewGroup
subclasses. These are the foundation that Android developers use to organize and group their View
objects (UI elements) on the smartphone display screen.
Direct subclasses of the ViewGroup
class include AbsoluteLayout, RelativeLayout, FrameLayout, LinearLayout
, and SlidingDrawer
. We'll look at the two most often used ViewGroup
subclasses: LinearLayout
and RelativeLayout
. We'll also explore one of the coolest ViewGroup
subclasses: SlidingDrawer
. This subclass can be used to greatly expand your Android screen real estate by 200%.
In the diagram in Figure 6-1, the top level ViewGroup
object is the parent of the View
objects and ViewGroup
objects underneath it, which are called its children. The ViewGroup
object in the second row is both a child as well as a parent, and the same goes for the ViewGroup
object in the third row.
As you can see, ViewGroup
objects can contain other ViewGroup
objects (a concept called nesting; it's all so familial, isn't it?), but View
objects cannot contain other objects. They are the end object, so to speak, and are simply UI components for which you can set via a plethora of configuration parameters.
The primary way of defining screen layouts (I will stop calling them ViewGroup
objects now, assuming that you are now classifying them as such when you see the term) is via XML. This XML goes inside a file called main.xml, placed inside a folder called /res/layout within your project folder.
Once this main.xml file is in place, with your XML screen layout (UI) definition inside it, you can use the Java onCreate()
method to push it onto your screen on the startup of your application activity, as discussed in Chapter 5.
We'll first take a look at the onCreate()
code and how it works, and then we'll use it for real in the next sections, where we will create three vastly different types of screen layouts.
Just three lines of Java code inside an onCreate()
method set your content view to the main.xml screen layout XML definition:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
The words before the method name determine who can access its methods and data. A public
method is one that is open to any part of your Android application.
The words that follow the method name (always enclosed in parentheses) are the parameters that an application can pass to the method for its use. Parameters are chunks of data the method needs to do its job.
The savedInstanceState
object is a Bundle
object, which is a collection of all of the states for your activity screen UI elements. It exists so that the screen UI elements can be restored if the screen is replaced by navigation to other screens during the use of your application. As you learned in Chapter 5, the state of a UI screen consists of its attributes and their values, including the UI elements it uses, which one has the focus, the colors, and similar attributes that define its appearance.
The Activity
class saves your state for you, so you don't need to worry. Simply extend it, and it does the work for you.
The super
keyword calls the superclass (the class containing the onCreate()
method that was subclassed from android.app.Activity
), so it is basically referencing the onCreate()
method of the android.app.Activity
class from which our activity class was subclassed. It's just a shortcut for android.app.Activity.onCreate(savedInstanceState)
. Since it is called from this activity class, it affects this activity locally and applies to this activity only. This savedInstanceState
object is the one Android kindly saves for us when it deals with saving state.
If you ever want to save some state that is out of the ordinary, write your own method called onSaveInstanceState(Bundle savedInstanceState)
. Then save your custom state to the savedInstanceState
object, remembering to call super.onSaveInstanceState(savedInstanceState)
.
The onCreate()
method will always be called by the Android operating system when any activity (remember that these are defined in the AndroidManifest.xml file) is started. This part of your code is where all of your initializations and UI definitions will be performed, so it must be present—at least if you need your users to interact with the smartphone screen area.
The way that layouts contain other nested layouts in XML code (as shown in Figure 6-1) is by nesting them inside each other. The closing tags are nested at the bottom of these structures, and they must be nested in the correct order to show Android which layouts are inside of which other layouts. Layouts underneath or inside of another layout conform to, and are controlled by, their parent layout container. The code examples in this chapter indent the nested code structures to show the nested layout hierarchy.
You are about to see all of this in action in the next section, where we'll work with the most commonly used layout container in Android: the linear layout. We'll talk about the LinearLayout
class, which has been subclassed from the ViewGroup
class, which is subclassed from the View
class, which is subclassed from the Object
class.
Java implements subclasses so there is no redundancy in the construction of your code. Once a method has been written, it is available to every subclass (and its subclasses) that inherits from its base class.
In a layout, usually buttons are placed across the top of the screen, or sometimes down the side of the screen, in a line. This is exactly what the LinearLayout
class does. It is designed to contain and arrange UI elements placed inside it across the screen (using the horizontal orientation parameter) or up and down the screen (using the vertical orientation parameter).
The LinearLayout
container should not contain any scrolling views. (I think that's common sense, but some folks will try anything once.)
In Java code, to set the LinearLayout
object's orientation, use the setOrientation(integer)
method, with either the constant HORIZONTAL
for horizontal or VERTICAL
for vertical:
myLinearLayout.setOrientation(HORIZONTAL);
After the LinearLayout
has been set up in your XML, it's possible to change its orientation on the fly inside your Java code.
Recall that constants are hard-coded values that your Java code uses in its program logic and can't change. In this case, Android provides easy-to-remember names so that you don't need to use fiddly numbers. You use the name HORIZONTAL
, rather than the value it is set to, which is 0
. This also helps if the value of HORIZONTAL
ever changes. You're protected because the name does not change, even if the value inside Android does.
Here's the attribute for orientation in the LinearLayout
tag for XML:
android:orientation="vertical"
Thus, the entire LinearLayout
tag looks like this:
<LinearLayout android:orientation="vertical">
However, we should really have a few more key parameters in the LinearLayout
tag to make it more useful and standardized, so here's how it's normally coded:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal">
The first parameter of the LinearLayout
XML tag is the path to the Android XML schema definition. This parameter sets the variable android
used in the rest of the tag to http://schemas.android.com/apk/res/android
, so that you don't need to write the other parameters like this:
http://schemas.android.com/apk/res/android:layout_width="fill_parent"
The value for the layout width and height parameters, fill_parent
, simply tells the LinearLayout
to expand to fill its parent container. Since this is the top level LinearLayout
container, that would mean to fill the smartphone display screen. We already know what the orientation does, so now we have our LinearLayout
defined. Anything we place inside this container will display across the screen from left to right.
As discussed earlier in the chapter, the Java onCreate()
method is used to load the main.xml layout parameters for the application.
Well, it's time to fire up Eclipse again, and create an application to see how all of this cool stuff works together.
We'll build a simple UI that stacks some TextView
elements along the left side of the screen, just to see how LinearLayout
works. Let's fire up Eclipse and get started!
After you launch Eclipse, you will be presented with a Workspace Launcher dialog, where Eclipse will present you with a suggested workspace folder. Alternatively, you can select your own folder. I created a C:Projects folder for my Android projects, and I used the Browse button to find this folder and select it, as shown in Figure 6-2.
After you have set your project folder, and Eclipse has launched its development environment, select File
Once you have created an Android project, there will also be other options, such as an Android XML File option and an Android Test Project option.
Now we need to create a new project resource, so hit the Next button. This takes you to the New Android Project dialog, where you need to fill out six important elements:
Project name: In this field, enter LinearLayouts
. This is the Eclipse project name, as well as the name of the folder that will hold all of the project files. We'll set the name of our application in this dialog as well.
Build Target: For our build target, we want as much platform compatibility as possible, so we choose support all the way back to Android 1.5. This way, our app will also work on Android versions 1.6, 2.0, 2.1, 2.2, 2.3, and 3.0. Version 1.5 equated to package release 3, as you can see in the middle area of this dialog.
Application name: In the Application name field in the Properties section, enter LinearLayout_Example. This is the name that will appear under our icon and in the title bar of our application.
Package name: In the Package name field in the Properties section, enter linear.layout
. (Remember that the package name is at least two names separated by a period.)
Create Activity: Make sure the Create Activity check box is checked, and type LinearLayoutActivity
in that field.
Min SDK Version: Enter 3, which matches the table in the middle of the dialog.
Figure 6-5 shows the completed dialog. Click the Finish button after you've filled out the fields.
Note that Eclipse Galileo has a bug where the compiler thinks the /gen folder is not created. But as you can see with a look at the expanded Package Explorer pane shown in Figure 6-6, the /gen folder is in fact present, and contains both files and data.
/gen is the compiler-generated folder, and not to be touched in any way during development.
Now it's time to work on main.xml. Right-click main.xml (if it is not open in a tab already) and select Open. You will see some default XML code setting up a linear layout with vertical orientation and a text field. Here is the code, which also appears in the main.xml tab shown in Figure 6-6:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
In this file, add another TextView
object by copy and pasting the <TextView>
element.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /><TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
We will edit the text strings to say "Text Area One!" and "Text Area Two!."
The text strings are edited in the strings.xml file, found in the values folder (shown in the Package Explorer). Right-click strings.xml and select Open
, so it opens in its own tab in the editing area.
Change the hello
text to Text Area One!
. Also add another string variable textareatwo
and set it to Text Area Two!
. Here's the code:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="textareaone">Text Area One!</string> <string name="textareatwo">Text Area Two!</string> <string name="app_name">LinearLayout_Example</string> </resources>
Figure 6-7 shows the strings added to the file.
Notice that the app_name
string was added from the information you gave in the project-creation dialog, so you don't need to code this (but this is where you change the app_name
later, if you want to).
Next, change main.xml to reference the textareaone
and textareatwo
string variables, which we set in the strings.xml file in the previous step, as shown in the code and in Figure 6-8.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/textareaone" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/textareatwo" /> </LinearLayout>
Now it is time to take a look at what our Java code is doing. Right-click the LinearLayoutActivity.java file on the left in the Package Explorer and select Open
.
REMEMBER there is another way to open a file for editing in its own tab: just select the .java or XML file and press the F3 key. A tab will open showing the contents of that file.
The file opens in its own tab next to the main.xml and strings.xml tabs in Eclipse. Here is the code (Figure 6-9 shows what it looks like in Eclipse):
package linear.layout; import android.app.Activity; import android.os.Bundle; public class LinearLayoutActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
As you can see, the package name that we defined in the New Android Project dialog is declared at the top of the Java code, as well as two import
statements that reference the Java classes that are needed (accessed or used) in the Java code: the Activity
class and the Bundle
class. Below this is the Java code that loads the XML layout that we created earlier in the other two tabs.
Now we are ready to compile and run our Android application. Since we have already set up our 1.5 phone emulator in Chapter 3, all we need to do to compile and run our app is right-click the top-level LinearLayouts project folder in the Package Explorer on the left and select Run As
In Figure 6-10, you can see the process that the Android compiler goes through to compile and launch your app in the 1.5 emulator. After around 30 seconds or so of loading, the emulation environment will launch your app (click the Home and/or Menu buttons on the emulator to see it). Note the name of the project and the name of our activity as they are loaded into the emulator.
Figure 6.10. View of Eclipse IDE with LinearLayout Java code and Console Tab Complier Progress Output
You'll see that the LinearLayout
vertically stacks our text fields as expected, as shown in Figure 6-11.
Relative layouts are for more complicated UI layouts for which you need to define the UI elements in a not so linear fashion. The RelativeLayout
layout class allows you to define how the UI elements (the View
objects) are to be placed on the screen relative to each other, rather than just laid out linearly. For this reason, the XML definition contains a few more variables, so this example will be a number of lines of markup code longer than the LinearLayout
example.
If you start to get into the habit of nesting several LinearLayout
containers to achieve a more complex UI layout result, you may want to consider using a single RelativeLayout
container to achieve the same results with better control.
Simpler is always better, so if you can write a UI layout using fewer nested ViewGroup
containers, it will always use less memory and function more quickly. The RelativeLayout
container allows you to arrange all sorts of UI elements together in a single ViewGroup
to achieve a complex layout.
Relative layouts are also the optimal type of layout container for using sliding drawers, another direct subclass of the ViewGroup
class. Sliding drawers extend the screen real estate of the smartphone by allowing drawers to slide out onto the screen from any of the four sides (top, left, bottom, or right). This is very cool functionality that is built into the Android SDK, as you'll see in the next section.
Since we already have our linear layout application open in Eclipse, let's change it to a relative layout configuration. That way, we won't need to type in all the same code. To change a layout, all you need to do is to change the XML code in your main.xml file.
Since our Java code references main.xml, we do not need to change anything in the LinearLayoutActivity.java tab to make these changes work, a testimony to the power of modularity via XML in Android. We also do not need to change (or even remove) the content in strings.xml, even though it will not be used in the application anymore.
If the unused code were lines of code in Java, Eclipse would notice that these variables were not used and warn you about it.
We'll edit main.xml now. And while we are at it, we'll also add some other UI elements—an editable text field and a couple buttons—so that you can see how easy it is to create (or in this case, change and/or refine) a UI inside Android.
In the first tag of main.xml, change LinearLayout
and its closing tag to RelativeLayout
. We will add some UI elements to the inside of the tag (before the closing tag </RelativeLayout>
line of markup code).
Let's leave in one <TextView>
tag and delete the other. Give the remaining tag an ID and a default, or starting, text value. So, this can be specified not only via a reference to a data declaration in strings.xml (as in our previous example), but also directly, right here in the main.xml file (just to show you two ways to do it), as follows:
<TextViewandroid:id="@+id/label"
android:layout_width="fill_parent" android:layout_heightfill_parent"android:text="Type here:"/>
This is the first UI element, so we don't have any relative layout attributes—there is nothing for this UI element to be relative to yet.
Next, let's add an <EditText>
element (either by typing it in or by dragging from the visual layouteditor tab), as follows:
<EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/label"/>
It will be laid out relative to (below) the TextView
as shown. The key line of XML is the parameter called layout_below
, which references the ID of the TextView
, telling Android to position the EditText
object below the TextView
object. This is pretty straightforward logic and also very powerful.
Now let's add an OK button UI element, via the <Button>
XML tag, as follows:
<Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/entry" android:layout_alignParentRight="true" android:layout_marginLeft="10dip" android:text="OK"/>
This <Button>
tag shows some of the power of relative positioning. The button is below the EditText
(using the parent's ID
parameter), aligned right relative to the parent, and with 10 pixels of margin to the left of the button.
To see this 10 pixels of spacing, let's add a Cancel button to the left of the OK button and aligned with it on the top, using this code:
<Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@+id/ok" android:layout_alignTop="@+id/ok" android:text="Cancel"/>
Here is all of the new RelativeLayout
code in the main.xml file (Figure 6-12 shows it in Eclipse):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:"/> /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/label" /> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/entry" android:layout_alignParentRight="true" android:layout_marginLeft="10dip" android:text="OK"/> <Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@+id/ok" android:layout_alignTop="@+id/ok" android:text="Cancel"/> </RelativeLayout>
Now let's compile the project. Right-click the LinearLayouts project folder at the top of the Package Explorer pane and select Run As
Now let's add some animation to our UI by creating sliding drawers for our UI elements.
One of the more advanced layout containers in Android is SlidingDrawer
, another direct subclass of the ever so useful ViewGroup
class. This layout is not used as often as the others, but it's extremely handy.
Sliding drawers are useful because they give us a way to expand the screen area that can be used by UI components, or even for application content, for that matter.
A SlidingDrawer
should be used as an overlay inside either the RelativeLayout
container or the FrameLayout
container. You cannot use SlidingDrawer
as its own container, because it needs to slide out of something.
FrameLayout
is not as useful as Linear
or Realtive
Layouts, and as such, is not as frequently used as a layout container type. It can be used to hold a single UI element inside a frame.
How do sliding drawers expand your screen area? By sliding a drawer (vertically or horizontally) onto the display from off the screen, you have another virtual screen available to use. This can be useful if you need the entire screen for your content, because you can keep your UI controls in a drawer that slides on or off the screen whenever it is needed.
Now let's add a sliding drawer to our RelativeLayout
of the previous section and see just how cool an application we can create in less than 20 lines of XML code. We'll create an app with an analog clock that slides out inside its own drawer whenever we need to see what time it is.
Leave the RelativeLayout
XML tag intact, but delete the text and button elements inside it. Then replace it with the SlidingDrawer
tag:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android android:layout_width="fill_parent" android:layout_height="fill_parent"> <SlidingDrawer android:id="@+id/drawer" android:layout_width="320dip" android:layout_height="440dip" android:orientation="vertical" android:handle="@+id/handle" android:content="@+id/content"><ImageView
android:id="@+id/handle"
android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/icon" />
<AnalogClock android:id="@+id/content"
android:background="#D0A0A0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</SlidingDrawer> </RelativeLayout>
As you can see from the code indenting, the SlidingDrawer
tag goes inside the RelativeLayout
tag. It has two other XML tags that go inside it: one that defines the graphic that will be used as the handle for opening and closing the drawer (the ImageView
tag), and another that defines the content inside the drawer (the AnalogClock
tag).
Since Android installed a default icon.png graphic (for use as an application icon) in our /res/drawable folder when we created our project for this chapter, I used that 48 × 48 pixel (standard size) icon for the handle of the drawer for demonstration purposes. Any size graphic can be used. You'll learn how to replace this with something cooler once we get to using graphics with Android in Chapter 8.
We need to set the layout height and layout width for this handle to match the PNG resolution using a setting of 48 device independent pixels (dip). We also need to point the ImageView
tag's file source parameter, android:src
, to the drawable folder and the icon file name, via @drawable/icon
. Note that we do not need to specify the resources folder /res/drawable or the full file name icon.png, because Android knows that @
means /res/, and we just need to specify the first name of the PNG file for a graphic image.
The other XML tag that must be inside any SlidingDrawer
layout container is content
. Whatever XML tag you want to use for your content must have an ID specified that matches the name that is specified in the SlidingDrawerandroid:content
parameter. In this case, we are using content
as the content container's ID, but it could be anything you like.
We are going to use Android's AnalogClock
XML tag to give us some impressive working content for this exercise. Note that we are accomplishing this in only four lines of XML code. In fact, this entire "clock in a drawer" Android application is using primarily XML and essentially no Java logic, other than to display the UI design on the smartphone screen.
So that we can see the boundaries of the SlidingDrawer
, which we have set in the SlidingDrawer
tag layout_width
and layout_height
parameters, we have placed an android:background
parameter in the AnalogClock
tag. The content is given a teaberry color background that matches our 1.5 emulator phone. This analog:background
parameter will work in virtually any XML tag relating to the screen and uses standard hexadecimal color value representation inside quotes.
Finally, click the strings.xml tab and change LinearLayout_Example
to SlidingDrawers_Example
.
Figure 6-14 shows the IDE with the new code ready to compile. I have spaced it out so that you can see which XML tags and modules are nested inside each other.
Figure 6-15 shows the sliding drawer example running in the emulator. Some cool things to change so that you can see what this layout container can do are the orientation (horizontal or vertical) and the layout width and height parameters of the SlidingDrawer
tag itself. I suggest that you practice compiling and testing Android applications by changing these XML parameters and then choosing Run As
Padding adds spacing to a view so that a view's content is offset by a certain number of pixels on each of the four sides. This way, the content doesn't touch the edges of the view and look unprofessional. In other words, padding adds space around the outside of a view's content, and you can choose to do so on any of the four sides of the view. When using padding, the padding is considered to be part of the view, which may affect the way Android lays out the view.
Padding values are only available to View
s, not to ViewGroup
s (and thus not available in screen layout containers). ViewGroup
s instead support margins, which allow the same results as padding to be obtained, except that the margins are not considered part of the ViewGroup
. For me, this makes UI design more organized and easy to remember: Views
use padding values and ViewGroup
s use margin values.
Padding can be set via your Java code using the setPadding()
method with four values, for left, top, right, and bottom. Think of going around a clock, starting at 9:00 AM, separated by commas. So, to put a 4-pixel border inside your view, you would use the following (remember that the order of parameters is left, top, right, bottom):
setPadding(4,4,4,4)
You can also separate each side in the Java methods. So, to get the padding for the left side of the view, use getPaddingLeft()
. To set just the padding on the top to 8 pixels, write this:
setPaddingTop(8)
For ViewGroup
s, including layout containers (the subject of this chapter), the easiest way to set margins during development is via the XML parameters for any ViewGroup
object.
Four layout margin values are available in XML:
android:layout_marginBottom
android:layout_marginLeft
android:layout_marginRight
android:layout_marginTop
We used one of these in our RelativeLayout
example earlier in this chapter.
Be sure to experiment with using these four parameters on your UI elements. You'll see that you can control exactly how your UI elements are spaced around on the screen as you become familiar with what margins can do.
Android allows us to design screen layouts via XML, which makes it much more simple than it would be via Java code. Nonprogrammers like designers can get involved with the UI design without needing to know Java.
In this chapter, we started to take a look at the foundation for laying out our UI areas on the Android smartphone screen using the View
and ViewGroup
classes. We use the ViewGroup
class and its subclasses to lay out our UI screen elements. Android provides several of these subclasses, including the LinearLayout, SlidingDrawer
and RelativeLayout
classes we looked at in this chapter.
LinearLayout
is the most used layout container in Android programming and the one used in the Android apps that come with the operating system. It arranges UI elements from right to left or top to bottom. It is possible to nest LinearLayout
containers within each other to achieve more complicated UIs.
RelativeLayout
is the next most used layout container in Android programming. It allows you to arrange UI elements by specifying their placement on the screen relative to each other. This allows for more complicated UI layouts than just the rows or columns supported by the LinearLayout
class.
We also took a look at one of the more innovative ViewGroup
layout containers called SlidingDrawer
. This allows you to slide UI elements on and off the screen, in and out of view. This layout container can be used to greatly increase screen real estate by allowing UI elements to exist off-screen in a "drawer" that slides out only when the user needs it.
In the next chapter, we will look at adding UI elements into our ViewGroup
layout containers using View
objects called widgets. The android.widget
package gives us all sorts of precoded UI elements.
44.200.94.150