Tuesday, July 8, 2014

Linear Layout

In Android, a LinearLayout is a layout that arranges screen components in a vertical or horizontal manner, via the orientationattribute. In addition, the component having the highest “weight” will fill up the remaining space of the LinearLayout.
In this tutorial, we shall learn how to use LinearLayout to display 3 buttons in vertical and horizontal order, and also how the “weight” attribute works.

1. LinearLayout – Horizontal

Open “res/layout/main.xml” file. Change the layout to LinearLayout. Set the android:orientation attribute to “horizontal”. Add 3 buttons within this layout. In this case, the highest weight is assigned to “Button3″, hence it will fill up the remaining space in the layout.

File: res/layout/main.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="horizontal" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 3"
        android:layout_weight="1"/>

</LinearLayout>


The output will be as follows :

2. LinearLayout – Vertical

Now, change the android:orientation attribute to “Vertical”.
File : res/layout/main.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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="Button 3"
        android:layout_weight="1"/>

</LinearLayout>

The output will be as follows :


No comments:

Post a Comment