Android: Creating TableRow rows inside a TableLayout programatically

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

Advertisement

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 http://www.anddev.org. 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 anddev.org, 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(R.id.maintable);

        // 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.setId(100+current);
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));   

            // Create a TextView to house the name of the province
            TextView labelTV = new TextView(this);
            labelTV.setId(200+current);
            labelTV.setText(provinces[current]);
            labelTV.setTextColor(Color.BLACK);
            labelTV.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            tr.addView(labelTV);

            // Create a TextView to house the value of the after-tax income
            TextView valueTV = new TextView(this);
            valueTV.setId(current);
            valueTV.setText("$0");
            valueTV.setTextColor(Color.BLACK);
            valueTV.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            tr.addView(valueTV);

            // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
        }

The main.xml contains the following for the TableLayout:

        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:stretchColumns="0,1"
                android:id="@+id/maintable" >
        </TableLayout>

And here is the final result:

image

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

19 Comments

  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!

    Thanks!

    Steve

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

    hello,
    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(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
    ” from each textview, something is displayed.

    Try it!

  4. pula
    July 2, 2010 at 22:14

    macaufuns,

    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.

    labelTV.setTextColor(Color.WHITE);

    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 row.so it takes too much time to load content and show in the page.please send suggestion to my mail how to improve my performance.
    krishnaprasadnagamalla@gmail.com
    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(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
    and
    valueTV.setLayoutParams(new LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));

    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(r.id.blabla)…

  18. Douglas
    August 2, 2012 at 13:41

    Awesome buddy! Thanks… You rock!

  19. Abhinav
    February 28, 2013 at 08:00

    Great and thanks a lot for this favour…..

    You Rock Man….
    Astix Android Team!

Leave a comment

Standard Login

Options:

Colors

  • o todo poderoso download baixaki
  • download sims 3 expansion packs online
  • van coke kartel download free mp3
  • gramps morgan album download
  • download option file pes 6 isl terbaru
  • ellie goulding download be mine
  • maroon 5 misery download video
  • download blue foundation life of a ghost
  • sonar notification download
  • cima f2 free download
  • snapbacks and tattoos remix download mp3
  • moves like jagger mp3 download 320kbps
  • nokia 2690 download photos
  • download package dependencies
  • download dragon ball ultimate battle 22
  • 2010 free download microsoft word
  • download talking parrot for nokia 5233
  • download anang feat aurel
  • download acapella rick ross
  • download linkedin for blackberry 9780
  • pergilah sepi download free
  • download rainha betsy
  • hunter hayes download free
  • lynyrd skynyrd download album
  • papi sanchez enamorame download
  • 2719400317
  • download juice itc font free
  • download git new workdir
  • iron man 3 download game
  • download lagu erie susan jangan dekati aku
  • phoenix lasso mp3 download
  • energy bliss visualization download
  • drools 4.0 download
  • download liga inggris
  • download tutorial sqlyog
  • hangover 2 download piratatuga
  • free download pcdj software full version
  • january tuesday our jewel download
  • popcorn song hot butter download
  • download rocket man the definitive hits
  • download filme corinthians 100 anos
  • shuttle bound meadowed isle download
  • amanecer parte 1 download subtitulada
  • download miễn phí yahoo messenger
  • download uncle tom's cabin by harriet beecher stowe
  • currency rate download free
  • drupal download database
  • statement form download
  • paczka mp3 download 2012
  • awarapan movie download 3gp format
  • after effects 5 download
  • bari arakeel download mp3
  • fifa 05 download full version pc free
  • netbeans 6.5 1 download
  • abba instrumental download free
  • unknown devices download windows 7
  • kat deluna download mp3
  • download chocolate with nuts
  • download pokemon diamante visual boy advance
  • streets of rage 2 download pc
  • download mirc untuk mobile
  • download koleksi lagu spin
  • ios 6 ipad 3 download chip
  • download anatomia em radiologia e tomografia
  • stoned mp3 download
  • download homepage metin2
  • must download films
  • download susan kay phantom
  • hana ringtone download
  • download pervasive 2000
  • ar eddy bear download
  • download mkvmerge per mac
  • download sme server 7.6
  • download naruto shippuden 130 sub indo
  • hef ft major gone download
  • download bre sempurna
  • horrible histories series 1 download
  • 1640 printer driver download
  • download for 300 violin orchestra
  • movie download hollywood in hindi
  • 4914947832
  • download challan 281 in excel format
  • download free bend it like beckham songs mp3
  • download abc 4 kids workshop free
  • chipset zero red-o-matic download
  • cso wallhack 2012 download
  • nfs 3 tracks download
  • download videos gangnam style
  • 1853085656
  • cheloo sau download fisierul meu
  • 100 love 3gp download
  • osthi mp3 songs free download zip
  • impossibile download file da internet
  • download dansk stavekontrol word 2010
  • eve client download
  • urdu joomla download
  • download student office 2010
  • download soft logitech pro 9000
  • sofer stam font download
  • download sharepoint 2010 nuggets
  • alegria en fundita download
  • nhpc admit card download trainee exam
  • unic remaja download
  • download psp harvest moon hero of the leaf valley
  • galaxy tab to download mode
  • download pb web launcher
  • frog's theme chrono trigger download
  • cometbird download for mac
  • download roberto carlos emoções
  • cdz ultimate cosmo mugen download
  • download dust frank ocean mp3
  • oracle companion 10g download
  • unison square garden orion download
  • free download robo video songs in telugu
  • siti download musica yahoo
  • jr dread jogi download
  • atmosphere deluxe 7.1 download
  • download traffic travis free
  • cannibal musical download
  • download dark go locker theme
  • download chris rene young homie
  • bücher download media markt
  • download singam movie of ajay devgan
  • download zawgyi unicode for mac
  • basler ip finder download
  • caindo na estrada download dublado rmvb
  • download brandy who i am
  • download zelda oot music
  • minecraft download kostenlos vollversion
  • download po form
  • download kreayshawn like it or love it
  • download pokedex alle 493 pokemon
  • download ichigo vs ulquiorra 3gp
  • bukkit 1.4.6 update download
  • ibm viavoice crack download
  • download barbie moda e magia rmvb
  • download khia been a bad girl
  • download internet tv & radio player
  • download hand history
  • download bittersweet within temptation
  • cad download eaton
  • download craft bukkit server 1.2.5
  • download logon changer for windows 7 free
  • download tranda la lume din nou
  • download full crypt raider
  • download bộ sách đĩa effortless english
  • rtpn aftershock download
  • lock up preet harpal download free
  • csd teach me dougie download
  • download epic rap battles of history cleopatra
  • 12 sky download failed
  • download mockingbird song eminem
  • download uso står her endnu
  • kindle 3g download
  • download free kp500 themes
  • surya s o krishnan songs download telugu
  • lgb 1.42 download
  • download vanilla bf2
  • wcw songs download
  • download meus dias no cairo
  • download chat yahoo dtdd
  • surface byte tags download
  • download program bandoo
  • v -station vst download
  • to reach you download anja
  • sky falls down download
  • lucky download jason mraz free
  • lineage 2 hellbound download gamershell
  • download pat martino linear expressions
  • download basic bbm
  • como fazer download no wareztuga
  • download bes 5.0 sp2
  • download fifa 06 tieng viet
  • download goa song lyrics
  • download berliner philharmoniker digital concert hall
  • nestle ice cream logo download
  • download albums lil wayne
  • tabel nrc pakan download
  • download echo360 presentation
  • download narcisa mi-e greu fara tine
  • starter boys noize download
  • unity for justice download
  • flashing cursor download
  • sketchflow styles download
  • for today breaker download blogspot
  • bitter virgin english download
  • sermons paul washer download
  • opm download websites
  • filezilla download windows 7 client
  • cyberlink youcam download effects
  • criminal minds download season 5 free
  • n ball free download chip
  • canon lide 200 download mac
  • 1429667032
  • download shades by sterling knight
  • download foxit latest version
  • dsl download zu langsam
  • bus download bus simulator
  • firefly driver download
  • download ost sherlock holmes 2009
  • 7793823032
  • download todo cambia mercedes sosa
  • free download video gurbani shabads
  • download speeds are really slow
  • pillar open your eyes download
  • hoodie allen leap year download datpiff
  • rm 505 n97 download
  • download smb all stars blur
  • mirror writing jamie woon download 320
  • download fring uiq
  • which itunes download for windows 7 64 bit
  • parrot ls 3200 download
  • download lagu cinta itu buta gratis
  • street legal redline crack download
  • download facebook hack attack 5.1
  • download segredos de uma novela
  • download ss501 snow prince mp3
  • sobi2 v card template download
  • download thai english dictionary free
  • download zindagi gulzar hai ost mp3
  • plans death cab download
  • muppets party cruise ps2 download
  • download mtp samsung galaxy
  • download nba 2k13 save game editor
  • goods delivery note template download
  • level d 767 download
  • purple rain download jailbreak
  • shoutcast dans 1.9.8 download
  • 6854947155
  • download dane cook comedy free
  • download playback lazaro um sentimento novo
  • download be calm
  • download buku awaken the giant within
  • download war commander cheat tool v1.02 exe
  • javascript disable download
  • wine encyclopedia download
  • download brush adobe photoshop cs
  • freepbx framework module download
  • dança com tudo download mp3
  • siti download basi musicali
  • mario kart pj64 download
  • skype 2.7 version download
  • winbox download now
  • dban disc download
  • tiara mp3 free download
  • download latest networking software
  • download allah wallpaper
  • download amrita rao
  • fried green tomatoes ost download
  • download de pequena sereia 2
  • download malicia segunda temporada
  • leonardo da vinci biography download
  • download trinh duyet internet explorer 8.0
  • limite vertical download dublado rmvb
  • download odbc gratis
  • gpu tweak utility download
  • download patch idm 519
  • download xlive update gta iv
  • download ideal lite
  • siam shade tribute download album
  • 3d warehouse download button missing
  • dee winamp download
  • cocoa system download
  • 7zip download org
  • act practice exam download
  • bake sale album download
  • my morning download wxpn
  • download app nokia 5800
  • download launcher for android 2.3
  • is 20gb download limit enough
  • xp boot screens download free
  • download file palette lmp
  • free download immigrant song led zeppelin mp3
  • download fashion design world
  • download cancer bats birthing the giant
  • download brick breaker revolution for mobile
  • download este habana - zumba mp3
  • heroes lore 3 download 240x320
  • desenhos dos anos 80 download
  • download sou seu fã numero 1
  • download installshield for visual studio
  • free download of spin and win game
  • ikm java test download
  • buddha hoga tera baap download
  • free download of asianet theme music
  • download honeycomb for notion ink
  • download sat nav for laptop
  • icarly iscream on halloween download
  • gilberto gil unplugged download free
  • deconstruction devin townsend project download
  • new star soccer download iphone
  • 9250066150
  • mozilla firefox download quickly
  • grenade alexa goddard mp3 download
  • powerdirector 10 tutorial book download
  • lagu lagu asli melayu download
  • download anomaly warzone earth
  • download villa free movies
  • download zro straight profit
  • download game shark 5 iso
  • 8261466772
  • halo loop 3 download
  • download seus satio
  • download zotac firestorm vga
  • download athena nu than chien tranh
  • william boyd download
  • download class actress bienvenue
  • zedd clarity extended download
  • custom story download amnesia dark descent
  • rush hour 720p download
  • never scared bonecrusher download mp3
  • download swizz beatz million bucks
  • lili creator download
  • download cruisin d'angelo
  • download on screen russian keyboard