A layout resource defines the architecture for the UI in an Activity or a component of a UI.
res/layout/filename.xmlView (or subclass) resource.R.layout.filename@[package:]layout/filename
<?xml version="1.0" encoding="utf-8"?> <ViewGroup xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/name" android:layout_height=["dimension" | "fill_parent" | "wrap_content"] android:layout_width=["dimension" | "fill_parent" | "wrap_content"] [ViewGroup-specific attributes] > <View android:id="@+id/name" android:layout_height=["dimension" | "fill_parent" | "wrap_content"] android:layout_width=["dimension" | "fill_parent" | "wrap_content"] [View-specific attributes] > <requestFocus/> </View> <ViewGroup > <View /> </ViewGroup> </ViewGroup>
Note: The root element can be either a
ViewGroup or a View, but there must be only
one root element and it must contain the xmlns:android attribute with the android
namespace as shown.
android:idFor the ID value, you should use this syntax form: "@+id/name". The plus symbol,
+, indicates that this is a new resource ID and the aapt tool will create
a new resource number to the R.java class, if it doesn't already exist. For example:
<TextView android:id="@+id/nameTextbox"/>
You can then refer to it this way in Java:
findViewById(R.id.nameTextbox);
android:layout_height and
android:layout_width:The height and width value can be expressed using any of the dimension units supported by Android (px, dp, sp, pt, in, mm) or with the following keywords:
| Value | Description |
|---|---|
match_parent |
Sets the dimension to match that of the parent element. Added in API Level 8 to
deprecate fill_parent. |
fill_parent |
Sets the dimension to match that of the parent element. |
wrap_content |
Sets the dimension only to the size required to fit the content of this element. |
You can create your own custom View and ViewGroup
elements and apply them to your layout the same as a standard layout
element. You can also specify the attributes supported in the XML element. To learn more,
read Building Custom Components.
res/layout/main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
This application code will load the layout for an Activity, in the
onCreate() method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView.(R.layout.main_activity);
}