In this post I will be discussing about the different view layouts in an android mobile application. The six different layouts are

1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View

Download Code

Android allows you to create view layouts using simple XML file (we can also create a layout using java code). All the layouts must be placed in /res/layout folder.

Android Layout Directory

Okay, now lets get started with the view layouts.

 

1. Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is an example of the linear layouts), either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.

Example of Vertical layout snippet

<LinearLayout android:orientation="vertical"> .... </LinearLayout>

Example of Horizontal layout snippet

<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Android Layout

Now that we know the two types of linear layouts, here are the steps you need to follow to create them

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “linear_layout.xml
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “linear_layout.xml”) and type the following code.

<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
  			android:text="Email:" android:padding="5dip"/>
  			
  <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
  			android:layout_marginBottom="10dip"/>  			
  
  <Button android:layout_width="fill_parent" android:layout_height="wrap_content"
  			android:text="Login"/>
  
  <!-- Child linear layout with horizontal orientation -->
  <LinearLayout android:layout_width="fill_parent" 
                      android:layout_height="wrap_content"
  		      android:orientation="horizontal" android:background="#2a2a2a"
  		      android:layout_marginTop="25dip">
  				
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
  		 android:text="Home" android:padding="15dip" android:layout_weight="1"
  		 android:gravity="center"/>
  			
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
  		 android:text="About" android:padding="15dip" android:layout_weight="1"
  		 android:gravity="center"/>	
  
  </LinearLayout>
    
</LinearLayout>


4. To set this newly created view as the initial view of your app, Open your MainActivity.java file. You would see the following line inside the onCreate function setContentView(R.layout.main). Change R.layout.main to R.layout.yourlinearviewname. In my case its R.layout.linear_layout

package com.example.androidlayouts;
import android.app.Activity;
import android.os.Bundle;

public class AndroidLayoutsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear_layout);
    }
}

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created linear layout in the emulator.

Linear layout output

2. Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to the right of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment (Right of Login button parallely)

Example code snippet

<Button android:id="@+id/btnLogin" ..></Button>

<Button android:layout_toRightOf="@id/btnLogin"
            android:layout_alignTop="@id/btnLogin" ..></Button>
Android relative layout

Here are the steps to create a relative layout

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “relative_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “relative_layout.xml”) and type the following code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content">

    <TextView android:id="@+id/label" android:layout_width="fill_parent" 
              android:layout_height="wrap_content" android:text="Email" />

    <EditText android:id="@+id/inputEmail" android:layout_width="fill_parent" 
              android:layout_height="wrap_content" android:layout_below="@id/label" />
  
    <Button android:id="@+id/btnLogin" android:layout_width="wrap_content"
    		android:layout_height="wrap_content" android:layout_below="@id/inputEmail"
            android:layout_alignParentLeft="true" android:layout_marginRight="10px"
            android:text="Login" />

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btnLogin" 
            android:layout_alignTop="@id/btnLogin"  android:text="Cancel" />
            
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    		android:layout_alignParentBottom="true" android:text="Register new Account"
    		android:layout_centerHorizontal="true"/>
</RelativeLayout>

4. Same like before open your MainActivity.java file and set the layout to your newly created relative layout file. In my case its R.layout.relative_layout


        setContentView(R.layout.relative_layout);

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created relative layout in the emulator.

Relative layout output

3. Table Layout

Table layouts in Android works in the same way HTML table layouts work. You can divide your layouts into rows and columns. Its very easy to understand. The image below should give you an idea.

Table layout

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “table_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “table_layout.xml”) and type the following code.

<TableLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:shrinkColumns="*"  android:stretchColumns="*" android:background="#ffffff"> 
    <!-- Row 1 with single column --> 
    <TableRow  
        android:layout_height="wrap_content"  
        android:layout_width="fill_parent"  
        android:gravity="center_horizontal">  
        <TextView  
            android:layout_width="match_parent" android:layout_height="wrap_content" 
            android:textSize="18dp" android:text="Row 1"  android:layout_span="3"
            android:padding="18dip" android:background="#b0b0b0" 
            android:textColor="#000"/>  
    </TableRow>  
    
    <!-- Row 2 with 3 columns -->
    <TableRow  
        android:id="@+id/tableRow1"  
        android:layout_height="wrap_content"  
        android:layout_width="match_parent">  
        <TextView  
            android:id="@+id/TextView04" android:text="Row 2 column 1" 
            android:layout_weight="1" android:background="#dcdcdc" 
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>  
        <TextView  
            android:id="@+id/TextView04" android:text="Row 2 column 2" 
            android:layout_weight="1" android:background="#d3d3d3" 
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
        <TextView  
            android:id="@+id/TextView04" android:text="Row 2 column 3" 
            android:layout_weight="1" android:background="#cac9c9" 
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
    </TableRow> 
    
    <!-- Row 3 with 2 columns -->
    <TableRow  
        android:layout_height="wrap_content"  
        android:layout_width="fill_parent"  
        android:gravity="center_horizontal">  
        <TextView  
            android:id="@+id/TextView04" android:text="Row 3 column 1" 
            android:layout_weight="1" android:background="#b0b0b0" 
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
            
        <TextView  
            android:id="@+id/TextView04" android:text="Row 3 column 2" 
            android:layout_weight="1" android:background="#a09f9f" 
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>  
    </TableRow>  
    
</TableLayout>

4. Same like before open your MainActivity.java file and set the layout to your newly created table layout file. In my case its R.layout.table_layout


        setContentView(R.layout.table_layout);

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created table layout in the emulator.

table layout output

I have just discussed Linear Layout, Relative Layout and Table Layout in this post. The remaining Grid View, Tab Layout and List View will be covered in the next article. Stay tuned!

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Vijayamannava1

    Nice artical…thabkyou…

    • Tinhphit

      thanks so much

  • Vijayamannava1

    Nice artical…thabkyou…

  • Vijayamannava1

    Nice Article…Thankyou

  • Pingback: Android Tutorials – Android Tab Layout Tutorial | Explicit()

  • kk

    nice….easy to understnd with the help of digrams….!!!

  • Grsandhya

    superb easy to learn thanks

  • Android

    Owsum Post….

  • Ruthgicharu2

    Nice!!! grateful for this post

  • X_bomb_x

    Thx it very cool.

  • Thanh Trung

    Thanks. This tutorial is very usefull!
    Hope you have many tutorials like this.

  • Hobby 110

    Nice tutorial…

  • Gudeamit148

    awesome man

  • Nm15

    Great work explaining this. Im taking an online Android class, and you covered this theme with far more clarity than the class im paying for.
    Again thanks

  • Edie

    U R awsome … Great job and amazing work

  • Amaaaaaaaaazing !

  • Madhu54108

    Splendid work
    Explanation with images is the very good way..
    Thank you

  • Raouabenfredj

    This tutorial is very clear, but when I put in a TableRow: 4 textview in the same colum colum and who is near him I just want to put 4 EditView. known me how I can achieve it.pleeeeeease :)))

    • try to place a EditText after textview and see how it comes.

      • abbasi.android

        hi ,
        i want to solve an expression , by using calculator in android
        i just want to click the required numbers and operators
        and want to solve the expression , in text view
        hw could i?

  • Dung Nguyen

    thanks, but where is “4. Grid View, 5. Tab Layout, 6. List View”? More please

    • I already wrote them. Please go through pagination of this blog.

  • Ramiz Mohamed

    Does not come any better than this. Much appreciated.

  • Ramiz Mohamed

    Very comprehensive but simple enough to understand. Well done.

  • Mahesh Anil Thokala

    [I18N] Hardcoded string “Email:”, should use @string resource.
    i got these warnings how i can remove.please help me.

    • Yes this warning is in new Android OS. You shouldn’t hard a string in XML instead you need to store the value in strings.xml and use that name here

      Like When creating new project in default main.xml, there will be hello string (project title).

      • Mahesh Anil Thokala

        I got another warning “This text field does not specify an inputType or a hint” But output comes in emulator,thaaaanks alot,you helped me alot……….

  • Luis Alberto Baigorria Rodas

    Hi. Ravi Tamada! Do you have any example multi-touch with a image in Android. I need it! Please! Congratulations for Androidhive! Very Good examples! Regards from Santa Cruz, Bolivia!

  • Thank man! Help me a lot

  • Hey Ravi Tamada

    What program you use to design picture

    i want to use design my layout icon

    Thank you ^^

  • Ravi Tamada

    i have problem

    i want to create custom Layout

    LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayoutTest);
    setContentView(ll);

    but error

    you can help me?

    thank you ^^

  • Manas

    Really it is a demo that marked as superb. I am salute the author for a great job.
    pls. keep it up

  • Nitesh Malviya

    baap sir…..

  • Pingback: Android Tab Layout Tutorial()

  • yoj

    thanks.. really helps..keep it up newbies here

  • Yakub

    Excellent….

  • Sameertm

    sooooooooooperb

  • jitendra

    Great posted tutorial ..excellent ……………….

  • Thanks man..Great tutorials

  • Mokamoddo

    This is just perfect. Thanks RAVI. You’re the man.

  • Gandi Gangadhar

    xmlns means xml namespace…….., what is the use of it

  • Tuan

    Thank Ravi so much

  • Bad2Guy

    thank for beginner

  • Mahalakshmi

    super

  • Sur

    Best Android Tutorial site ever

  • Thanks a ton for your article, everything is clearly explained

  • yungyung

    Thank you for working

  • Funjabiwala

    u r the boss… i am really fan of this site..thanks a lot

  • 516613535

    the TableRow’s child TextView’s android:layout_width is match_parent,why it doesn’t fill up with its parent??

  • Siva Brahma

    It is very nice simply superb.

  • Vijjumailto

    thank u so much good article.

  • sumit garg

    i want to know how to set Layouts using only java coding not by xml file.

  • Please how can bring all this table to start from the bottom up.

  • kartheek

    mind blowing, awesome, easy way to learn

  • Harish Thakur

    good

  • Mitulgoti001

    very good sir ji

  • Viswa

    Excellent !!

  • Steve

    It has helped me a lot.

    Thanks a lot

  • Deekshit

    Its really amazing article. Thanks for making the article as simple to understand. 🙂

  • rehaman

    thanks a lot ravi….i getting easy

    • tieudongta

      thank u very much

  • I am surprised to see GridView and ListView as listed in types of Layouts.

    And
    1. GridLayout is also available from API 14.
    2. what about FrameLayout which is there since API level 1?

  • Pavithakavin

    explanations are too good.very useful for me.
    thank u so much

  • Bappahgarga

    sir, what are the different between linear layout and table layout?

  • deepu

    Thanks a lot…it was neat and clear demo…fantanstic

  • Softsnmm

    thanks, I think…. I will be succ

  • Shaikhjuberk

    really dude u r superub it really helps a lot………thank you.

  • Jyoti Maimt

    thnkss…..itsss help me lot………….

  • Akkinenisurekha

    hey ravi could u tell me differences about relative & table

  • Chokoste

    thanks very helpful

  • S Kumar2958

    Hi Sir,

    Your blogs is very nice and most helpful for us. I request to you please upload more about android and if you have such PDF ebook , Please mail me . My mail Id is s.kumar2958@gmail.com. I will wait your response , Please help me.

    • Suresh

      alert(“Web Site Hacked”);

      • Jarod

        wow! How did U do that?!!!! 🙂 Haker pierwszej wody

    • suhail

      hello

      please if you got some PDF or ebook please foreword it to me on suhail.ryadi@gmail.com

      regards

  • gunjan verma

    Good Post…………….. keep it up……………

  • gunjan verma

    Good Post…………….. keep it up……

  • praki

    thanx……..

  • Zealtolearn

    Really its informative..thanks for describing with example.

  • Prashant Hirapara

    I wanted to clear this confusion about different layouts and this just did that…loved it…thanks !!

  • Can Uludağ

    That is a great explanation

  • Raiyani sagar

    thanks…

  • Durga

    Blog is more useful,,,,need more updates

  • Maya Saif

    great job thanks

  • Quanghits

    Great tutorial.

  • go open source

    AMAZING TUTORIAL …. I LIKE IT..

  • Caracola

    Great explanation. Thanks!

  • pavan deshpande

    Pavan

    @ (http://www.pavanhd.blogspot.in/)

    You May Also Like this
    android linear layout

  • Roneykakkanatt
  • thanks so much

  • Dharam

    Great Demo. its Awsome!

  • vishal

    thannx

  • Faraz Ahmad

    Very helpful….

  • GIang

    What is the function of shrinkColumns?

  • Fiyas

    Learn ANDROID from ANDROIDITUTS

    http://www.androidituts.com

  • Umesh

    You are simply superb

  • vadd

    TnankU!

  • smart@sunil

    as a beginner its good

  • Abhimanyu

    nice yr……..

  • Ravikumar

    Wow ! i got it in one shot …………………. thnx

  • Chu Myat Moe

    very clear explaining. Easy to realize and give useful knowledge. Thz a lot. 🙂

  • Dariush

    tnx 🙂

  • Murali

    it’s nice article to beginers…thanks

  • Meghna

    Thanks man.. Nice examples.. Even this
    http://www.compiletimeerror.com/2013/06/android-linearlayout-example.html might help, have a look…

  • KAlyan

    awesome dude!!

  • Harshal Voonna

    How do i have a progress bar on top of my imageview

  • why google hasn’t mentioned about the table layout here…http://developer.android.com/guide/topics/ui/declaring-layout.html

  • Akbar

    GREAT JOB! Thanks for these awesome articles.

  • Rohan Rana

    reallyy…thanku veryy muchhh

  • aldson diego

    Thanks. This tutorial is very good!

  • Akshay

    Thanks alot for the post it is very clear and easy to understand!!

  • Ashish Kumar Singh

    good explanation.. 🙂
    thanks..

  • bhavesh

    very nice demo

  • yourkishore

    You really dont know how much this helped me thanks alot, i know you from 9lessons also, i thing you are brother of srinivas tamada, Appreciate your both works.

  • James

    I don’t normally bother replying to these kind of things but I wanted to compliment your clear explanation of these features. I am currently going through all of your tutorials even though I have a few years of experience in other areas (php/mysql/c#/asp/jquery/css/flash) and I think your tutorials are excellently explained. Thanks a lot for contributing to the internet in a positive way!

  • Muskaan Sharam

    fantastic tutorial.. the way, you explained is very easy and much more understandable.. Thanks

  • Nusrat

    Nice Introduction 🙂

  • Arthur

    I’ve been using this one in case you don’t want to specify a specific item of focus

    InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);

    inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);

    • Thanks Arthur 🙂

    • Pritish Joshi

      Got this error
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.os.IBinder android.view.View.getWindowToken()’ on a null object reference

  • Dev

    Nice……….thank u.

  • Abdul Wahab

    Easy and Informative

  • Muhammad hussain

    How you can design this sketch layout. I want to do this for my project work. Help me please to do my wireframe alike. Thank

  • nikhil

    thanks super easy !

  • Arun

    Really Superb..!!

  • ben

    I love u…really!!!!
    Was searchin for this kinda explanation. Noone could explain except u…:*

  • gopi

    U R GREAT

  • Sandun Abeywickrama

    Thank u !!!

  • Yusuf Yak

    Wonderful…this one of the best android tutorial site in the WORLD!!!!!!!!!

  • Jobin

    Well explained….

  • The Power of Love

    Thank you! This really helped me figure out how I could achieve what I wanted to do.

  • Thank you Ravi 🙂

  • A way from Away

    Thank you its very helpful

  • gonza28

    Thanks for your tutorials and resources. Congratulations

  • farooq shaik

    great .. code well i didnt understand whats its application i just implemented in my code .. where a user in put some text and press button that text will go to server and previously in my app even after pressing button keyboard use to be visible. one of my co- devloper(habeeb) did complained about this and i ignore it till today. i have added this code to make keyboard invisible arthur code when user presses the button and keyboard goes out from view

  • Binh Vova

    Thanks you Ravi 🙂

  • thanks, i just start learning about android programming, and your site i think is very good for me to learn about android programming

    • core

      absulitiy rite

  • Thanks for the article, but you should really get rid of all your “fill_parent” strings and replace them with “match_parent”. Both of these do the same thing and so including both in the same source file like you did just adds to confusion. “fill_parent” has been deprecated in favour of “match_parent” since API level 8 and in fact both resolve to the same constant, -1.

  • dinesh

    i am very beginner in android. im really impressed with ur tutorials..good job

  • vikas balyan

    great job..

  • fiqkyrahman

    good job

  • AMBIKA

    Good Man

  • mohid

    Well done.. 🙂

  • krip

    What tool do you use to draw these mock-up?

  • sujeethkumar

    Really superb nice tutorial……

  • Why not take a look at my blog about how to create an Android app that displays an Image in an ImageView control of the main Activity at the full width of the screen.

    The app uses the following Android SDK objects:

    . ImageView
    . LinearLayout
    . Bitmap
    . Activity
    . XML layout
    . LayoutParams
    . Display

    Also:
    . layout_width
    . layout_height
    . orientation
    . id
    . vertical
    . match_parent

    XML attributes and values are covered.

    Click the link BELOW! to see

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner.html

  • Why not take a look at my blog about how to create an Android app that displays an Image in an ImageView control of the main Activity at the full width of the screen.

    The app uses the following Android SDK objects:

    . ImageView
    . Bitmap
    . LinearLayout
    . Activity
    . XML layout
    . LayoutParams
    . Display

    Also:
    . layout_width
    . layout_height
    . orientation
    . id
    . vertical
    . match_parent

    XML attributes and values are covered.

    Click the link BELOW! to see

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner.html

  • If you would like to learn how to use the following objects to write an Android application that displays a vertically upward scrolling Rainbow of colours in a FREE video, then click the link at the end of this comment:

    . LinearLayout
    . Activity
    . View
    . Canvas
    . ArrayList
    . Paint

    http://androidprogrammeringcorner.blogspot.com/2015/06/pak-longs-android-programming-corner_24.html

  • ulaş

    but doesnt work galaxy tablet ?

  • Manvendra Priyadarshi Maan

    Use this if you are getting error : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.os.IBinder android.view.View.getWindowToken()’ on a null object reference
    _______________________________________________________________________________

    InputMethodManager inputMethodManager = (InputMethodManager) MainActivity.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
    if(MainActivity.this.getCurrentFocus() != null)
    {
    inputMethodManager.hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), 0);
    }

  • Escarcega Light

    Excellent, thanks :).

  • Hemalatha M.R

    I have used the layout without knowing its usage.. But now i cleared with this layout…Good Job

  • Shabana Parveen

    nice explanation. thanks 🙂

  • Shahab Sadeghi

    hi,tank you for your really good Site
    i have problem in third row,it dos not strech texboxes and left an empty column after tow texts.

    • Hi Shahab,

      TableView is just for your knowledge only. In real app table view is not much considered as best approach.