Android TableLayout Example with Code

android tablelayout exampleAndroid is a popular platform for designing touch-screen based device applications. It can run on different types of hardware and provides support for impressive graphics and makes optimum use of various device’s hardware capabilities. The Open Handset Alliance which includes major IT organization such as Google is constantly improving and developing this widely used programming language. As it is based on the Java programming language those who already know Java can easily migrate to this platform. This is an exciting technology which is dominating the mobile landscape.  A large community of developers is constantly developing applications for both entertainment and business purposes for Android smart phones. If you’d like to be part of the Android story, now’s a good time to get started. This course is a great place for beginners to learn about Android development.

Here in this beginner’s level tutorial  we look at a few TableLayout examples.  We assume that you have a basic knowledge about Java programming language. If not you may want to first check out Java essentials for Android with this course.

What is View Object

A View object is the foundation for the user interface of an Android application. This object is created from the View class. It provides support for drawing and event handling. It is also the base class for widgets which are used to create interactive UI components.  The ViewGroup class is derived from the View class and is used to hold other Views or other ViewGroups. It also defines their layout properties.  There are different types of layout supported by Android. They are as follows – linear Layout, relative Layout, list view, grid view, absolute layout, frame layout and table Layout. Learn more about the Android UI in this beginners course.

TableLayout in Android

A table layout is a grid which contains rows and columns. Table Layouts are ideal for displaying tabular data. It can be also used to neatly align items on the screen. You can use TableLayout to organize UI (user Interface) or widgets.  There is a table row control for each row in your table.

TableRow is a layout where its elements are horizontally arranged. This object must always be used as a child of TableLayout. The children of the TableRow do not need to set the layout_width and layout_height attributes. These values are permanently MATCH_PARENT and WRAP_CONTENT respectively. Let’s take a closer look at some of the important methods of this class. You may also want to check out this course to help understand Android Layouts better.

TableLayout Overview

The TableLayout in Android is very much like the <table> tag in Html. It arranges its children in rows and columns.  <TableLayout> tag is the parent element and <TableRow> tag is its child of the parent element. <TableRow> is used to store any view object such as text field, button and more. The TableLayout does not show the borderline for the cells, rows or columns.

The number of columns of the table is equal to numbers of columns of the row with the most cells. In Android cells can be left empty, but unlike HTML here cells cannot span columns. The width of a column is equal to the width of the widest cell in that column. Columns can be made shrinkable by using the setColumnShrinkable() method. If the column is made shrinkable it is possible to shrink the column width. This is done in order to fit the table into its parent object. Similarly, if you want to stretch a particular column, use the setColumnStretchable() method. If declared stretchable, the column’s width can be expanded to fit any extra space. If you wish to hide a column, use the setColumnCollapsed()method.

The children elements of the TableLayout are not allowed to set the layout_width attribute. The value of the width of a child element should always be MATCH_PARENT. A child can set the layout_height attribute. The default value is WRAP_CONTENT. In case, the child is a TableRow, the height is constant and is equal to WRAP_CONTENT. Note that cells are added to a row in increasing column order. In case you don’t specify a column number for a child, it will go to the next available column. If the column number is skipped that will be regarded as an empty cell of that row. You are permitted to use any View subclass as a direct child element of table layout.

TableLayout Example

Here’s a simple example to put together the pieces we’ve learned so far.

This is a basic tablelayout. The first row is very basic, with a single column. The second row has three columns, and the third row has two columns. In this example, we’ve just written basic text in each section. You could also have images, buttons, or anything else. Here’s the code for this example

<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="18dip" 
                                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="18dip" 
                                android:gravity="center"/>
                        </TableRow>
                         
      </TableLayout>

The code isn’t too complex, but to understand it better, you may want to take this course on Android development. We’ll also walk you through details of the TableLayout and TableRow classes we’ve used in this example.

Important Functions of TableLayout

Here is a comprehensive list of functions which belong to the TableLayout class.

  • TableLayout(Context context) – To create a new TableLayout use  this method. The Context parameter refers to the application environment.
  • TableLayout(Context context, AttributeSet attrs)- This method also creates a new TableLayout. However, here you can specify the collection of attributes.
  • addView(View child)- You can use this method to add a child view.
  • addView (View child, int index, ViewGroup.LayoutParams params) – This method adds a child view. It also accepts the specified layout parameters for the child. The “index” parameter specifies the position at which to add the child.
  • generateLayoutParams(AttributeSet attrs)- This function is used to generate a set of layout parameters determined by the supplied attributes set.
  • isColumnCollapsed(int columnIndex) – It gives the collapse status of the specified column. The “columnindex” parameter indicates the index of the column.

Important functions of TableRow

  • TableRow(Context context)- You can create a new TableRow using this function.
  • TableRow(Context context, AttributeSet attrs)- Use this function to create a TableRow with the specified attributes.
  • generateLayoutParams(AttributeSet attrs)-This function generated a new set of layout parameters.
  • getVirtualChildAt(int i)- This function is used to get the view at the specified index.
  • getVirtualChildCount()- You can use this function to know the virtual number of children.
  • setOnHierarchyChangeListener(ViewGroup.OnHierarchyChangeListener listener)-This function is used to register a call back. The latter is invoked when you a child is added or removed from this view.
  • onLayout(boolean changed, int l, int t, int r, int b)- This particular function is called from layout when this view needs to assign a size and position for each of its children. All the positions parameters passed are relative to parent. Let’s take a look at the position parameters.
  1. l       Left position
  2. t      Top position
  3. r      Right position
  4. b     Bottom position

Hope this article helped you understand the TableLayout in Android. Try out your own programs using TableLayout in order to master its use. If you need help at any point of time, you can refer back to this Android app development course.