Android: Creating TableRow rows inside a TableLayout programatically

Posted July 1st @ 10:07 pm by Boyan Tsolov


In my quest to create a “Taxman” Android application I ran into the following problem:

I want to ask the user to enter their yearly income, after which the screen will flip and their after-tax income will be displayed in a table format for all Canadian provinces. (And for the future: all US states). The problem I ran into is creating a TableRow for each Canadian province in my main.xml. There are 13 provinces and territories, so 13 is not that bad to copy & paste in the main.xml; however, as soon as I have to copy & paste more than 2 times I start cringing and nausea kicks in. Personally I think “copy & paste” should not be in the programming vocabulary. Not only that, but I have 13 provinces now, what about when I have to enter 50 states! So, I had to find a way to create these new TableRow rows programmatically inside my TableLayout layout.

A great source for code snippets and answers to Android questions is I’m sure if you’re dabbling with Android then you’ve already come across this site. The particular post I read to do this is this one: Dynamically add rows to TableLayout. Commenters on that post were having problems getting this to work, but after I imported all the correct classes (android.widget.TableRow.LayoutParams is an important one to use) everything worked from the first time. I forced Eclipse to find most of the classes for me.

Below is the code from, with my changes for my Taxman Android app. I’m too lazy to do a full-out beginning-to-end tutorial for this code snippet.

First I set my constants at the top of the Activity class:

public class Activity1 extends Activity implements OnTouchListener{

    int PROVINCE_Alberta = 0;
    int PROVINCE_BC = 1;
    int PROVINCE_Manitoba = 2;
    int PROVINCE_NewBrunswick = 3;
    int PROVINCE_Newfoundland = 4;
    int PROVINCE_Northwest = 5;
    int PROVINCE_NovaScotia = 6;
    int PROVINCE_Nunavut = 7;
    int PROVINCE_Ontario = 8;
    int PROVINCE_PEI = 9;
    int PROVINCE_Quebec = 10;
    int PROVINCE_Saskatchewan = 11;
    int PROVINCE_Yukon = 12;

    int numProvinces = 13;

There are 13 of them this time, there will be 50 of them for the States… technically this could be made into something much more malleable like an external config-type XML file.

Then in the onCreate method I created an array of String objects that will house all these provinces:

        String[] provinces = new String[numProvinces];
        provinces[PROVINCE_Alberta] = "Alberta";
        provinces[PROVINCE_BC] = "British Columbia";
        provinces[PROVINCE_Manitoba] = "Manitoba";
        provinces[PROVINCE_NewBrunswick] = "New Brunswick";
        provinces[PROVINCE_Newfoundland] = "Newfoundland and Labrador";
        provinces[PROVINCE_Northwest] = "Northwest Territories";
        provinces[PROVINCE_NovaScotia] = "Nova Scotia";
        provinces[PROVINCE_Nunavut] = "Nunavut";
        provinces[PROVINCE_Ontario] = "Ontario";
        provinces[PROVINCE_PEI] = "Prince Edward Island";
        provinces[PROVINCE_Quebec] = "Quebec";
        provinces[PROVINCE_Saskatchewan] = "Saskatchewan";
        provinces[PROVINCE_Yukon] =  "Yukon";

And right underneath that I create a TableRow for each item in the array provinces:

        // Get the TableLayout
        TableLayout tl = (TableLayout) findViewById(;

        // Go through each item in the array
        for (int current = 0; current < numProvinces; current++)
            // Create a TableRow and give it an ID
            TableRow tr = new TableRow(this);
            tr.setLayoutParams(new LayoutParams(

            // Create a TextView to house the name of the province
            TextView labelTV = new TextView(this);
            labelTV.setLayoutParams(new LayoutParams(

            // Create a TextView to house the value of the after-tax income
            TextView valueTV = new TextView(this);
            valueTV.setLayoutParams(new LayoutParams(

            // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(

The main.xml contains the following for the TableLayout:

        <TableLayout xmlns:android=""
                android:id="@+id/maintable" >

And here is the final result:


So far I have the Ontario taxes working :). If you make $50,000 in Ontario, you’d be taking home $38,285.53.

2 Trackbacks/Pingbacks

  1. Pingback: Android: Creating TableRow rows inside a TableLayout programatically - android xml ???? on December 15, 2010
  2. Pingback: Best way to present tabular data? on October 30, 2012


  1. Steve Glachan
    September 8, 2009 at 08:58

    This is close to what I am looking for!

    I have the table building dynamically, called from onCreate() … my problem is that the table shows MONTH based figures with a Spinner above it. You can choose a new month from the Spinner and the table ‘is supposed to’ update the the selected month’s data.

    If you know… could you point me in the direction to be able to do this? I don’t under stand how to clear the table and draw a new one programatically in it’s place each time the month is changed…

    Obviously, I’m a little new to Android. I’m a little disappointed at how difficult tables have been so far. I eventually want to populate the table from a sql query result set, but I’ll get to that later once the testing works!



  2. Paresh Mayani
    March 29, 2010 at 07:41

    i have tried this in my code for the demo of dynamically adding row to a tablelayout as such it may be very much helpful in my project.

    But i cant find anything on screen when i run it.

    pls suggest and make me out……

    Thanx in advance

  3. macaufuns
    May 26, 2010 at 05:14

    Paresh Mayani,
    I have the same problem, and then I remove “valueTV.setLayoutParams(new LayoutParams(
    ” from each textview, something is displayed.

    Try it!

  4. pula
    July 2, 2010 at 22:14


    that works for me too! I wonder why?

  5. Anond
    July 13, 2010 at 10:53

    I’ve got a force close when I tried to add the values to the table layout.. Anyone know why ? I’vent changed any part of the code.

  6. Anond
    July 13, 2010 at 10:58

    Nevermind… I I’ve put the wrong xml on the contentView

  7. Anond
    July 13, 2010 at 10:58

    Thanks by the way, you’ve helped me a lot

  8. LaszloLaszlo
    August 21, 2010 at 04:09

    macaufuns: I had the same problem when i imported a wrong LayoutParams class. Try importing android.widget.TableRow.LayoutParams

    br, Laszlo

  9. Kabilan
    December 31, 2010 at 02:55

    Good Tutorial !

    Initially I got plain black screen ie., nothing.

    Found out at last. Text color has been set to black and background colour hasnt been set.


    I think you can see it now : )

  10. J-ing
    January 7, 2011 at 00:15

    Hi, is it possible to hv this at the bottom?

    public boolean onTouch(View arg0, MotionEvent arg1) {
    // TODO Auto-generated method stub

    return false;

    cos if i wan to make it to be able to scroll, is there anything that i need to add on?

  11. rahul
    February 9, 2011 at 01:29

    Hi basically we dont need to set layout for textView controls in the above example .

    Just remove that one ant tried it works fine .

  12. Krishna prasad
    February 24, 2011 at 02:35

    Hi,In my project also i used same logic, but i have a lot of data(content) to show in the form of table it takes too much time to load content and show in the page.please send suggestion to my mail how to improve my performance.
    thank u.

  13. Zack
    March 10, 2011 at 17:02

    This is a great post. However, is it not possible to just create a table_row.xml that defines a single TableRow, and then inflate that and just populate it, as opposed to having to write out all the attributes in Java?

  14. Dhara
    April 8, 2011 at 04:24

    I use above code for tablelayout I got force close when run the application. I also debug code it go in catch block from sentence table.addView(tableRow);
    Help me. Thanks in advance.

  15. Vidhi
    October 3, 2011 at 04:51

    In regards to the solution provided for the table row to show up (i.e. by removing the setLayoutParams for the TextView), how would i do it, if i have a long line of text.
    I tried removing the text wrapping, but then i lose part of my text too. Can anyone help me with this?
    For my entire text to show up, i wud need layoutparams to be wrap_content for my TextView

  16. dunghv
    October 10, 2011 at 19:34

    hi, i try your example on android 3.0, but i don’t textvie on screen. when, i comment code line:
    labelTV.setLayoutParams(new LayoutParams(
    valueTV.setLayoutParams(new LayoutParams(

    textviews is show, how do use textview.setLayoutParams
    thanks help me!

  17. muzaffer
    June 5, 2012 at 10:20

    Dhara! I was having same problem, too. Do not forget to initialize tablelayout by tl = (TableLayout) findviewbyid(…

  18. Douglas
    August 2, 2012 at 13:41

    Awesome buddy! Thanks… You rock!

  19. kirit
    December 30, 2013 at 07:50

    Really very helpful

  20. Tarun
    July 31, 2014 at 06:03

    Here is a link i have taken help from it to use table layout Adding DYNAMIC TABLE ROWS IN TABLELAYOUT PROGRAMICALLY in android . It also contains files to download code

  21. adidas ?????
    August 4, 2014 at 04:50

    Rip DVD Movies to iTunes iPhone, iPad, iPod all deliver the same message and it is to stay connected to music and videos nonstop all the days of their life as long as the battery is in the device. It is also a very remarkable statistic that most youngsters of today are the people who are so glued into the trend of plugging something into their ears and hearing it all the time. What one must realize is that these are not the only devices that are in the portable entertainment market today, but there are a host of other accompanied which have glutted this industry with so many models leaving a very confused consumer unless he has done his homework and is quite certain about this requirements and tastes. Most often it is not taste that hinders but the warmth of one’s pocket that matters more. The advent of iTunes mp4 This is one of the most versatile container formats of this century and it owes its popularity to the fact that almost all devices, is they phones or other portable entertainment devices, is all compatible with this format. This mp4 is able to contain a wide variety of files and it is this fact that makes it such a adaptable and user friendly format with people. For example, one may download a movie in the mp4 format and then play a wide variety of subtitles in various languages all in addition to this and have a picture of the DVD cover on it as well. All these can be succinctly contained within a single file and this is the true genius of the mp4 format. All these require that any DVD which has been released be converted to an mp4 format so that it can be watched on the go anywhere and at any time with the ease of lounging from a bus chair or plopped up with pillows on a train. Conversion of files In order for a person to view these on portable devices, one has to ensure that his DVD is converted into the mp4 format as well and this is where Aimersoft’s software products come of use. This product is great to rip DVD iTunes without any hassle, since it comes with an inbuilt tutorial on how to convert DVD to iTunes and all the required steps are enumerated very lucidly so that one can complete his task with minimum amount of fuss and flutter. There are many dvd ripper iTunes available to a person and therefore it is wise to read a few reviews before stepping off ripping DVD to iTunes. This is an important step, simply because many people have stored movies on their DVDs but would like them to be out in the open on their portable devices, so that they can watch the movie in their free time. This being the strongest reason possible, one must consider the usage of this software so that he can complete his conversion quickly and watch his movie on the move. copy DVD to iTunes rip DVD into iTunes

Leave a comment

Standard Login



  • download centopeia humana legendado rmvb
  • each time mp3 download
  • download project eden game
  • download telephone ring sound wav
  • download latest counter strike 1.6
  • download tubidy app for blackberry
  • download mp3 peri cinta
  • filemaker pro 6 download mac
  • download map navitel terbaru
  • uffie make it hot download
  • iphone 4 vlog download
  • download my happiness powderfinger mp3
  • download tron bo hoai linh
  • download bot tibia 9.53
  • criadas y seAoras download duane
  • f a 18 super hornet demo download
  • hity 2011 download peb
  • download pokemon lavender town music
  • free download eddy wata i like the way mp3
  • download ios 6 to mac
  • sql developer modeler download
  • download dance dance dance boyfriend mp3
  • canon 20d zoombrowser download
  • download lagu jiraiya versi indonesia
  • download materi kelas 8
  • download wonder girls so hot
  • sholay mouth organ ringtone download
  • download tumhi ho bandhu sakha tumhi ho
  • download wale hate is the new love
  • free download dekh tamasha lakdi ka
  • download obra de mozart
  • download greta knights new world order
  • download a longa viagem de volta
  • download cfw 3.55 da sony
  • download 7 icons playboy video
  • download avaya java device manager
  • susan boyle download mp3 free
  • prince of persia 2 download free
  • download together as one lucky dube
  • wpe download without virus
  • download ebook mencari tuhan yang hilang
  • download pokemon games vnsharing
  • exceed download windows xp
  • a fera vanessa hudgens download dublado
  • avery 64 bit download
  • ethernet controller windows 7 download free
  • download linksys wrt320n software
  • sacred peAna wersja download chomikuj
  • download lagu solat lima waktu
  • iti admit card download up
  • kokoro connect volume 5 download
  • download mankatha theme music free
  • download bahan ajar pkn smp
  • download maquina del tiempo wisin y yandel
  • kalafina live concert download
  • download template 2 kolom blog
  • 8 abs module level 2 download
  • download leftovers by prima j
  • der pate buch download
  • download nhl 09 addony
  • download london paris newyork songs for free
  • eastbound and down theme download
  • download about you now miranda cosgrove mp3
  • unable to download or save files
  • download 50 tons mais escuros livro
  • romanzo criminale download puntate
  • bt broadband help download mac
  • download dub be good to me
  • download iwifihack on ipod touch
  • download um quadro de nA?s dois
  • ddd pool game download free
  • download tears for fears mad world mp3
  • download jogo gtr 2
  • wicked way with you download
  • download pha?n ma?m ha tra? kA? khai 3.0
  • download bb5 easy service tool
  • download lagu remuk jantungku
  • download ot yurots 8.60
  • domace serije download besplatno
  • download donna summer on the radio mp3
  • naruto shippuden episode 215 download free
  • download driver sony vaio vgn p13gh
  • asus m2n68 se2 driver download
  • download edinburgh glasgow expansion pack
  • piratatuga download fm 2011
  • download private emotions mp3
  • game shark 5.0 download
  • matsushita yuya album 2u download
  • download youtube downloader 6.5
  • download r.p.g. maker vx
  • jace everett bad things download free mp3
  • download he has nothing but kungfu
  • download hitman contracts trainer
  • download lagu yang terlupakan aries
  • biostar p4m89 m7b driver download
  • download gmaps for nokia n8
  • download foodcourt waktuku belum terlambat
  • download mse for whs
  • download dragon ball z budokai hr free
  • download zedge ringtones your phone
  • download planeta terror rmvb dublado
  • ubuntu 11.04 os download
  • licence for download manager
  • download future juicy j i'm trippin
  • download physxextensions.dll for batman arkham city
  • whatcha say dubstep download quantum
  • download leitor de cartA?o banrisul
  • ms 6577 video driver download
  • mp3 download va va voom
  • rowdy rathore download songs
  • download aldous huxley heaven and hell
  • download renegado do oiapoque a nova york
  • download ebook revolution 2020 chetan bhagat
  • download cnet internet explorer
  • download how i met 7x13
  • matrix y2k download windows 7
  • download game shopping dress up
  • p 970 driver download
  • download lagu blast band
  • samsung gt b7722 manual download
  • free download to make your computer faster
  • maldita porque download mp3
  • download ile ijo by may d mp3
  • download james arthur lets get it on
  • download esto es calle lapiz conciente
  • download palavras repetidas gabriel o pensador
  • gnomon introduction to maya download
  • arno pro font free download windows
  • download visualization for media player
  • nokia e50 skype download
  • fs design studio 3 download
  • download vicky donor
  • james blunt goodbye download
  • minecraft singleplayer download kostenlos deutsch
  • download empire earth units
  • clear download from itunes
  • britney spears criminal download for free
  • download m indicator nokia
  • download free sadda haq rockstar
  • xbox live can't download update
  • download umd movies for psp for free
  • download west coast hustle
  • download zippy susanu numele tau
  • download temi per ubuntu
  • mundo estranho mortes misteriosas download
  • download dreamy baby collection for raw
  • download rapi.dll for windows 7
  • megaman zx download for pc
  • download yahoo fantasy football mobile
  • download world of tanks 0.7.0
  • download hit bollywood songs
  • error sending ram download for bootloader droid 2
  • v per vendetta download ita gratis
  • download lightning for thunderbird 12
  • veoh download how to
  • download tema tribal emerald windows 7
  • u and i hum tum download
  • download f1 racing game free
  • download gun bros for pc
  • counter strike 1.6 download jeje ge
  • mixcraft 5 download keygen
  • adriano sunet & viteza download
  • download sorry t.o. mp3
  • suikoden 5 download iso
  • anjo caido minecraft download gratis
  • download virtual villager 1 full
  • download jay chou hua hai
  • download assault rock mp3
  • garmin 760 manual download
  • download fonte word diva regular
  • bossa nova instrumental download free
  • download gangstar 2 galaxy y
  • download visual foxpro untuk windows 7
  • download sh' boom 5
  • b.a.p second album download
  • the teeth beneath download
  • download starcraft 2 launcher
  • download cartoon wars 2 heroes ipa
  • download voice to text converter software
  • download soundtrack la naranja mecanica
  • fratii reut album 2010 download
  • download the grapes of wrath epub
  • download hitam putih ada band
  • client tibia 8.54 download
  • download my cactus heart
  • summertime mos def download
  • download singularity full rip
  • can't stop maroon 5 download
  • download armv6 android games
  • download flood they might be giants
  • download 1080p bollywood video songs
  • free download maa non stop garba
  • badan pe sitare karaoke download
  • dearly beloved full download
  • mockingbirdill mockingbird editor 9 download
  • download amar swapna tumi
  • microsoft jscript editor download
  • ios 5 download no itunes
  • download home 3d design free
  • sA? para loucos cd download
  • download garmin 2010 maps
  • intel 2200bg driver download for windows 7
  • photofunia new version download
  • micky maus video download
  • download tablet windows 7
  • download mat danh iris thuyet minh
  • download blame it on ya x bandit gang
  • download windows 2003 vm
  • huong dan download heroes 3
  • wsc snooker game download
  • download love rain episode 8 eng sub
  • diarios de vampiro download 2 temporada
  • download up bihar lootne
  • download action replay update
  • download domino access for microsoft outlook
  • rumor has it download free mp3
  • download the duff ebook
  • download de thi hsg toan 8
  • download i love you quotes
  • download lagu hidupku bukannya aku lagi
  • mar jayian download song
  • subah subah ringtone download
  • der kleine lord download uploaded
  • negima nintendo ds download
  • download silkroad online game
  • justin timberlake discography download free
  • sunrise avenue download kostenlos
  • download driver for transcend pen drive
  • download photoshop cs5 partes
  • download twitterrific for desktop
  • download minecraft comes alive 1.2.5 installer
  • download airport madness 2 free
  • filip kirkorov disko partizani download
  • download sinners in the hands of an angry god audio
  • 13 assassins download hd
  • ethical questions in dentistry download
  • set theory book download
  • bat download file url
  • free download madura dictionary for windows 7
  • needless opening 1 full download
  • download first take theme song
  • download radar britney spears mp3
  • download musiq soulchild don't change instrumental
  • program za remix download
  • ubuntu download step by step
  • sketches of spain download
  • download cavalo de guerra hd
  • download lagu tangga kesempatan kedua free
  • download sisu bagabonti in tara minunilor zippy
  • download free alvin and the chipmunks movie
  • nvidia 8600gt download driver
  • download saves need for speed undercover
  • dragnet tv show download
  • download pokemon emerald on your computer
  • download donkey kong country 2 snes rom
  • download financial modeling with crystal ball and excel
  • yu gi oh download card
  • gak kayak mantanmu free download mp3
  • presario cq60 software download
  • love comes rising download
  • download gundam ms igloo 2
  • download hp d1360 printer driver free
  • download qt 3.3 for windows
  • overexposed download maroon 5
  • download school days episode 1
  • robert duncan fired up download
  • download the reign ja roule
  • f1 09 game free download
  • download roller coaster 3d rush
  • download black berry messenger 7
  • download mein shayar to nahin
  • download iisadmin.mfl for windows 2003
  • zug simulator free download vollversion kostenlos
  • hyde faith live dvd download
  • download phim nha?t thac hd
  • silly boy download rihanna
  • download the mastery of love free
  • sims 2 exe crack download
  • opera mini download pc free
  • mahadev ki baraat download
  • scx 4623f driver download mac
  • oracle gateways 11g download
  • dias de truta download
  • download thomson tg585 v7 software
  • download castelo animado dublado
  • download balao magico super fantastico
  • amigo da onAa download dublado
  • download vodafone mobile connect 10.2
  • two towers download movie
  • php oop ebook download
  • download song juttni punjabi
  • download phim meo oggy
  • download zhu zhu pets game
  • download bobcat gta sa
  • free download apsara aali video song
  • sabita vabi limbs download
  • india martinez 2012 download
  • download ceca 2011 album
  • download geisha cukup tak lagi gudang lagu
  • download anita blake comics free
  • download oracle 10g standard edition
  • ballad of goddess download
  • download hellsing dublado 3gp
  • download free nokia 7610 pc suite
  • download alkitab windows mobile 6.1
  • glee only exception download free
  • download 2 brooke shields season 1 free
  • download din shagna da
  • primerica financial needs analysis download
  • download kat graham against the wall
  • hit em up download free
  • download bakugan in gba
  • download mp3 cinta memilihmu
  • 4 2 0 kottonmouth kings free download
  • download swing jazz songs
  • download oppa oppa super junior
  • download life frame windows 7 free
  • the sims 3 download e installazione
  • download lagu galau indonesia terbaru
  • download zynga texas holdem for iphone
  • download il cavaliere oscuro il ritorno ita
  • hp pavillion dv1000 drivers download
  • download samurai deeper kyo op
  • stronghold 3 download free full game
  • blood c the last dark ost download
  • download irctc application on mobile
  • download future aint no way around it instrumental
  • mozilla firefox 1.0 7 download
  • download drive de rede
  • download swap magic 3.8 iso
  • microsoft forefront uag download
  • download rtet admit card
  • download mojo gba emulator 1.2
  • chase online banking download
  • download borderlands on pc free
  • brute force attack ubuntu download
  • ibrahim tatlAses vur gitsin download
  • battlefield 3 close quarters download time
  • lady gaga alejandro download kostenlos
  • download the gambler fun
  • download top 10 shooting games
  • free download lagu kahwin mp3
  • nokia n8 user manual announces download
  • download free mahadewi mengapa oh mengapa
  • crysis 2 gcf download
  • czas honoru 1 download
  • download po tej stronie raju
  • tanu weds manu movie download kickass
  • download voice of koyal
  • download kunci gitar wali nenekku pahlawanku
  • download lagu eun bi sarange dachyeoseo
  • download jasiek mbh nazwij to jak chcesz
  • battlefield 2 patch 1.41 download kostenlos
  • download lagu on the floo
  • incredimail xe download windows
  • are you in download
  • dire straits songs download free
  • 64 bit kmplayer download
  • skyrim pirata download pc
  • download fire emblem 7 rom 1235
  • download song dulhe ka sehra suhana
  • download asu din corason
  • download j# second edition
  • download rehab amy winehouse mp3 skull
  • download dragon ball vs street fighter free
  • download jota quest festival de verA?o 2011
  • fallout 3 keygen download
  • download project 64 the emulator zone
  • download dubba jonny vip tutorial
  • akon songs download 2011
  • download deva gana album
  • kruti dev 011 download font
  • antiwpa download windows xp
  • download gammu versi terbaru
  • x ray scanner free download htc
  • lg ks365 free download games
  • download arjunanya buaya mp3
  • quintal de monstros download
  • download hack metin 2fun
  • laos font download windows
  • lumidee could be anything download
  • download windows xp validation tool
  • esmee denters victim free download
  • lagu romantis barat download
  • download winzip 30 day trial
  • download mp3 berharap kau kembali
  • download internet explorer 13 vista
  • download chessmaster xi grandmaster edition
  • download song roya re shiraz uppal
  • download deliric inspectia tehnica de calitate
  • download livro eletronica digital editora erica
  • download leo the late bloomer
  • download lola monroe songs
  • reginaldo rossi download blogspot
  • download soundtrack iklan windows 8 versi india
  • smallville download todas as temporadas dublado
  • abrar ul haq download mp3
  • video games download online
  • 5230 themes free download nokia
  • idolm ster sp download plus