Android Linear Layout

Guest Posts coolbhushans

In Android, basic and very simple layout is linear layout. Using linear layout we can create complex layout structure. In Linear Layout every component is its children and layout aligns all its children’s into single direction i.e. Horizontal or Vertical. We can specify the directions using attribute android: orientation in xml.

Linear Layout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Default weight is zero

Calculation to assign any remaining space between children

space assign to child = (child individual weight) / (sum of weight of every child in Linear Layout).

Let’s see in code

Linear Layout Horizontal

1.Open activity_main.xml and insert following code in it.

 

 <?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> 

In this we have added weight for 3rd button as 1 so it will take remaining space.
ART8_image1

Simillarly we can create Vertical layout as Follows

Just change activity_xml to as follows

 <?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> 

ART8_image2