OK So What Does It Look Like

Here is the Button from the previous chapter's sample application, converted into an XML layout file, found in the Layouts/NowRedux sample project. This code sample along with all others in this chapter can be found in the Source Code area of http://apress.com.

<?xml version="1.0" encoding="utf-8"?>

<Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/button" android:text=""

android:layout width="fill parent" android:layout height="fill parent"/>

The class name of the widget—Button—forms the name of the XML element. Since Button is an Android-supplied widget, we can just use the bare class name. If you create your own widgets as subclasses of android.view.View, you would need to provide a full package declaration as well (e.g., com.commonsware.android.MyWidget).

The root element needs to declare the Android XML namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

All other elements will be children of the root and will inherit that namespace declaration. Because we want to reference this button from our Java code, we need to give it an identifier via the android:id attribute. We will cover this concept in greater detail later in this chapter.

1. http://droiddraw.org/

2. http://windowssdk.msdn.microsoft.com/en us/library/ms752059.aspx

3. http://www.adobe.com/products/flex/

4. http://www.mozilla.org/projects/xul/

5. http://www.zkoss.org/

The remaining attributes are properties of this Button instance:

• android:text indicates the initial text to be displayed on the button face (in this case, an empty string)

• android:layout width and android:layout height tell Android to have the button's width and height fill the "parent", in this case the entire screen—these attributes will be covered in greater detail in Chapter 7.

Since this single widget is the only content in our activity, we only need this single element. Complex Uls will require a whole tree of elements, representing the widgets and containers that control their positioning. All the remaining chapters of this book will use the XML layout form whenever practical, so there are dozens of other examples of more complex layouts for you to peruse from Chapter 7 onward.

0 0

Post a comment