LinearLayout With Examples
LinearLayout With Examples
In android, we can specify the linear layout orientation using android:orientation attribute.
In LinearLayout, the child View instances arranged one by one, so the horizontal list will have
only one row of multiple columns and vertical list will have one column of multiple rows.
If we observe above code snippet, here we defined orientation as vertical, so this aligns all its
child layout / views vertically.
Create a new android application using android studio and give names as LinearLayout. In case
if you are not aware of creating an app in android studio check this article Android Hello World
App.
1
Now open an activity_main.xml file from \res\layout path and write the code like as shown
below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity file MainActivity.java from \
java\com.sarker.linearlayout path and write the code like as shown below.
MainActivity.java
package com.sarker.com.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
If we observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main.
2
Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.
Output
When we run above example using android virtual device (AVD) we will get a result like as shown
below.
If we observe above example, we used three text fields and we assigned weight value to only one
text field. The two text fields without weight will occupy only the area required for its content and
the other text field with weight value will expand to fill the remaining space after all three fields
measured.
This is how we can use LinearLayout in android applications to render all View instances one by
one either in Horizontal direction or Vertical direction based on the orientation property.