Книга: Beginning Android
OK, So What Does It Look Like?
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.
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 UIs 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.