Tuesday, 2 July 2013

Android LinearLayout example

// siddhu vydyabhushana // Leave a Comment
In Android, LinearLayout is a common layout that arranges “component” in vertical or horizontal order, via orientation attribute. In additional, the highest “weight” component will fill up the remaining space in LinearLayout.
In this tutorial, we show you how to use LinearLayout to display 3 buttons in vertical and horizontal order, and also how “weight” works.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. LinearLayout – Horizontal

Open “res/layout/main.xml” file, add 3 buttons within LinearLayout, with “horizontal” orientation. In this case, the highest weight is “button3″, so 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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 3" 
        android:layout_weight="1"/>
 
</LinearLayout>
See figure :
android linearlayout demo1

2. LinearLayout – Vertical

Now, change the LinearLayout to “Vertical” orientation.
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="wrap_content"
        android:text="Button 3" 
        android:layout_weight="1"/>
 
</LinearLayout>
See figure :
android linearlayout demo2

Download Source Code

Download it – Android-LinearLayout-Example.zip (15 KB)

0 comments:

Post a Comment