LinearLayout
TheLinearLayout
arranges views in a single column or single row. Child views can either be arranged vertically or horizontally. To see how LinearLayout
works, let's modify the main.xml
file in the project:<?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>
main.xml
file, observe that the root element is <LinearLayout>
and it has a <TextView>
element contained within it. The <LinearLayout>
element controls the order in which the views contained within it appear. Each View and
ViewGroup
has a set of common attributes, some of which are shown in Table 1.Attribute | Description |
---|---|
layout_width | Specifies the width of the View or ViewGroup |
layout_height | Specifies the height of the View or ViewGroup |
layout_marginTop | Specifies extra space on the top side of the View or ViewGroup |
layout_marginBottom | Specifies extra space on the bottom side of the View or ViewGroup |
layout_marginLeft | Specifies extra space on the left side of the View or ViewGroup |
layout_marginRight | Specifies extra space on the right side of the View or ViewGroup |
layout_gravity | Specifies how child Views are positioned |
layout_weight | Specifies how much of the extra space in the layout to be allocated to the View |
layout_x | Specifies the x-coordinate of the View or ViewGroup |
layout_y | Specifies the y-coordinate of the View or ViewGroup |
ViewGroup
(s). For example, the layout_weight
and layout_gravity
attributes are only applicable if a View
is either in a LinearLayout
or TableLayout
.For example, the
<TextView>
element above has its width filling up the entire width of its parent (which is the screen in this case) using the fill_parent
constant. Its height is indicated by the wrap_content
constant, which means that its height is the height of its content (in this case, the text contained within it). If you do not wish to have the <TextView>
view occupy the entire row, you can set its layout_width
attribute to wrap_content
, like this:<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" />
<TextView android:layout_width="105px" android:layout_height="wrap_content" android:text="@string/hello" />
main.xml
file by adding a <Button>
view as shown below:<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:layout_width="105px" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:layout_width="100px" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>