Hello all,
Often we need to show data from a source such as a database in a tableView like we see in an HTML Page. In Android also we can do this with the help of TableLayout. We can create dynamic rows and add data to it.

Android Dynamic Table UI

MainActivity

package table_demo.coderzheaven.com.tabledemo;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    String companies[] = {"Google", "Windows", "iPhone", "Nokia", "Samsung",
            "Google", "Windows", "iPhone", "Nokia", "Samsung",
            "Google", "Windows", "iPhone", "Nokia", "Samsung"};
    String os[] = {"Android", "Mango", "iOS", "Symbian", "Bada",
            "Android", "Mango", "iOS", "Symbian", "Bada",
            "Android", "Mango", "iOS", "Symbian", "Bada"};

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

    private TextView getTextView(int id, String title, int color, int typeface, int bgColor) {
        TextView tv = new TextView(this);
        tv.setId(id);
        tv.setText(title.toUpperCase());
        tv.setTextColor(color);
        tv.setPadding(40, 40, 40, 40);
        tv.setTypeface(Typeface.DEFAULT, typeface);
        tv.setBackgroundColor(bgColor);
        tv.setLayoutParams(getLayoutParams());
        tv.setOnClickListener(this);
        return tv;
    }

    @NonNull
    private LayoutParams getLayoutParams() {
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(2, 0, 0, 2);
        return params;
    }

    @NonNull
    private TableLayout.LayoutParams getTblLayoutParams() {
        return new TableLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
    }

    /**
     * This function add the headers to the table
     **/
    public void addHeaders() {
        TableLayout tl = findViewById(R.id.table);
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(getLayoutParams());
        tr.addView(getTextView(0, "COMPANY", Color.WHITE, Typeface.BOLD, Color.BLUE));
        tr.addView(getTextView(0, "OS", Color.WHITE, Typeface.BOLD, Color.BLUE));
        tl.addView(tr, getTblLayoutParams());
    }

    /**
     * This function add the data to the table
     **/
    public void addData() {
        int numCompanies = companies.length;
        TableLayout tl = findViewById(R.id.table);
        for (int i = 0; i < numCompanies; i++) {
            TableRow tr = new TableRow(this);
            tr.setLayoutParams(getLayoutParams());
            tr.addView(getTextView(i + 1, companies[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
            tr.addView(getTextView(i + numCompanies, os[i], Color.WHITE, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent)));
            tl.addView(tr, getTblLayoutParams());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        TextView tv = findViewById(id);
        if (null != tv) {
            Log.i("onClick", "Clicked on row :: " + id);
            Toast.makeText(this, "Clicked on row :: " + id + ", Text :: " + tv.getText(), Toast.LENGTH_SHORT).show();
        }
    }
}

Layout

Below is the layout that actually holds the table in the layout.

Here is the activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    tools:context="table_demo.coderzheaven.com.tabledemo.MainActivity">

    <TableLayout
        android:id="@+id/table"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="0,1" />

</ScrollView>

Source code

You can download the complete source code from here.

 

18 Comments

  1. trugur January 31, 2012 at 7:15 pm

    Thanks a lot. I did this. However i want to get selected row values in the table. For example when i touched second row in above screen i want to get “Windows” and “Mango” values. How can i do this?

     
    • James January 31, 2012 at 8:12 pm

      @trugur:- Add a click eventListener to the textView and onClick get the view.getText(). that’s all.

       
      • trugur January 31, 2012 at 10:03 pm

        I tried but i couldn’t find gettext function. Can you give me a simple example?
        And this is what i have tried:

        tr.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        v.setBackgroundColor(Color.DKGRAY);
        v.showContextMenu();

        }
        });

         
        • James January 31, 2012 at 10:06 pm

          Don’t add listener for table row, instead add listener for the textview inside it. set it the id as same as the row number. So when you click on it, you will get the text in it and the row number which is it’s id.

           
          • trugur January 31, 2012 at 10:55 pm

            Thank you for your help.
            I added listener for textview. But now it gives me text of last row. I think i coudn’t do about id. I’m not so good about this subject. Could you give me simple example please? I’ll be glad.

             
          • James January 31, 2012 at 11:04 pm

            I will try.

             
  2. Drakot August 22, 2012 at 10:36 am

    I get nothing. No errors, but nothing displayed

     
  3. Amanda July 31, 2013 at 1:29 am

    Thank you for your post! It helped me alot! 😀

     
  4. Fahim Nasir November 9, 2014 at 12:27 pm

    It shows nothing, blank screen. Help..?

     
    • James November 10, 2014 at 5:27 am

      Did you check your php code is error free?
      if it is ok, try to print the response from the server in the Logcat.

       
  5. Flexicious July 11, 2015 at 7:50 pm

    Fully Customizable Rows and Columns with Support for Inline Filters, Summary Footers, Server/Client Paging, Sort, Excel/Word Export, Locked Columns, Inline Edit, User Settings Persistence and a lot more!

     
  6. Farrukh May 18, 2017 at 1:39 pm

    i am doing same but screen show nothing, help plzzzzzzzzzzz

     
  7. Farrukh May 18, 2017 at 1:44 pm

    also heaving error in “setContentView(R.layout.main);” as cannot resolve symbol ‘main’
    plzzzzz help

     
    • James May 20, 2017 at 6:35 pm

      Farrukh,

      This is because there is some error in the XML file. Please fix it and this error will go away.

       
      • Farrukh June 22, 2017 at 10:48 am

        Thanks
        fix it

         
  8. Surjan May 29, 2017 at 1:53 pm

    Thank you .. really helpful article

     
  9. Azadeh July 9, 2017 at 7:39 pm

    Thankfulllllllll
    🙂
    it`s very good

     
  10. Luc December 22, 2017 at 7:56 am

    Thank you !!!

     

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.