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

21 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. 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

    geeksprogrammings.blogspot.com/2014/07/xml-parsing-tablelayout-android.html

  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

Options:

Colors

  • black sex movies online
  • pornstar jamie lynn videos for sale
  • bikini round up online sex
  • free threesome online sex videos
  • halloween costume sex videos
  • video
  • video
  • video
  • anime ass fuck videos online
  • discount davids bridal flower girl dresses
  • teenage sleeping beauty halloween costumes
  • video
  • Sex and the city movie watch online
  • erotic lesbian short stories online
  • cheap rates for bon petite martin
  • sleeping beauty halloween costumes for teenagers
  • amateur australian woman online video choke
  • cheap mes oral sex toys
  • watch porn wars movie online free
  • free online sexy fuck videos
  • video
  • sunporno ebony thumgs
  • costume fuck videos
  • video
  • naked teens free online videos
  • video
  • girls geisha asian costume
  • video
  • sexy costumes on girls
  • hot girls in sexy costumes
  • free online asian teen sex
  • free online nondownloadable hardcore porn
  • sexy teen pirate costume
  • video
  • video
  • free online black teen porn videos
  • free porn movies online without downloadig
  • free online sex instructional videos
  • wife ordered naked
  • hot asian lesbians online
  • omg hes naked young celebrities
  • free teen sex videos online
  • teen girl fuck buys
  • free online young porn movies
  • watch free online pornstar movies
  • online lesbian anal
  • tube online video sex
  • girls gone wild free online video
  • movie character costumes for couples
  • online teen video
  • free online viewing sex movies
  • free online sexy naked girls
  • video
  • xxx sex vedios for sale
  • young as they cum video online
  • free online full length black pussy
  • freeonline teen videos
  • wholesale xxx hardcore dvds
  • video
  • petite womens golf shirts for sale
  • british porn vids free online
  • video
  • video
  • black porn videos online
  • kim kardashian full sex video online
  • japanese girls for sale
  • free online group sex videos
  • video
  • cartoon porn free online videos
  • sexy blonde girls online webcams
  • hardcore porn online
  • free pics nude girls costa rica
  • cost afterschool program la petite
  • girls fingering girls videos online
  • free online naked pictures of celebities
  • blowjob movies free online
  • free online pictures of erotic massage
  • free online porn full movies
  • brittney from dreamgirls porn
  • anal sex on megavideo online
  • free black movies online
  • free vergin online sex videos
  • free online celebrety sex videos
  • free online porn first time lesbians
  • fuck movies online free
  • young solo anal buy
  • Katie price nude pics
  • ebony lesbians free online videos
  • free online young girl porn
  • teen sex online
  • video
  • where can i order porn movies
  • free online amateur food sex videos
  • kakashis online free sex videos
  • desi porn videos online for free
  • Nude girls online
  • free asian xxx video online
  • little caprice anal on megavideo online
  • upsidedown girl online movie
  • free online fingering porn video
  • online mature hollywood movies
  • erotic stories wife salesman
  • free online porn sex videos
  • miss muffet teen girl halloween costume
  • free online erotic lesbian sex stories
  • free online porn mature black dick
  • xxx online sex stores
  • womens petite suits on sale
  • video
  • video
  • free online pussy licking
  • video
  • free shemale porn movies online
  • online videos of sex
  • free online sex stories with pictures
  • free online hardcore sexxx videos
  • free online sleeping porn vids
  • free erotic sex manga online
  • petite size halloween costumes
  • free online amateur sex tapes
  • video
  • homemade sex video wife lomgest
  • read free hardcore sex stories online
  • free online porn videos steaming live
  • shemale anime online free video
  • petite womens buy outfits
  • free online videos of sex slaves
  • download porn online video to computer
  • video
  • watch celeb sex videos online
  • video
  • discount vibrators for my pussy
  • free online teen nudism
  • wholesale black lesbian porn dvds
  • free online photos mature sexy ladies
  • video
  • massage erotic videos online
  • indian movie online naked
  • video
  • online movie babes in toyland
  • celebrity porn movies free online
  • free teen sex videos online
  • free online barchelor party porn
  • video
  • petite southwestern apparel online
  • anal complition on megavideo online
  • best mallu sex online video sites
  • buying asian type of sex toys
  • erotic lesbian love online
  • free amateur porn video online
  • oral sex and free dvds online
  • Sex scenes online
  • female free online stripping movies porn
  • video
  • concannon vineyard petite sirah price
  • blonde teen farmgirl
  • where to buy black sexlink chickens
  • online black amateur porn community
  • video
  • media player online free sex videos
  • young ethnic homebuyers
  • hbo movie asian mailorder bride bigamist
  • erotic young girls costumes
  • free ebony lesbian video online
  • Best boobs online
  • sexy girls in costumes pics real
  • bizzare sex videoss to buy
  • asian movie online streaming
  • free online homemade sex video
  • Sex incest price
  • Asian teen mgp
  • free online teen titan porn videos
  • video
  • ebony fucking videos online
  • teen blowjob video online
  • video
  • video
  • teen toys girls sale
  • time traveler wife free online movie
  • alsscan model littlecaprice pussy
  • Sex scenes online
  • video
  • free online fuck movies
  • sales petite gray pants
  • online porn video tubes
  • video
  • free online amateur porn video
  • video
  • video
  • video online free porn
  • calvin klein petite coats on sale
  • maxxcock free porn videos online
  • mature hairy german sleepimg pussy
  • sexy school girl costume canada
  • video
  • india porn video watch online
  • male porn videos online
  • online young teen models
  • black porn videos online
  • gary colemans wife shannon price pics
  • naughty teen girls in costumes
  • free indian online sex movies
  • costumed sex pictures
  • Nude pics of katie price
  • girls wholesale party dresses
  • cuckold mature black online
  • hottest girl videos online free
  • oral sex efor sale
  • wife deepthroating online video
  • anime porn free online videos
  • sue price sex pictures
  • free online porn video lesbian
  • video
  • online video of shemale sex
  • free erotic movies watch online
  • video
  • video
  • video
  • free online classic porn video
  • free hentai online sex videos
  • free online hairy pussy porn
  • final fantasy online with naked girls
  • video
  • streaming online ebony porn
  • video
  • young fuck old videos free online
  • video
  • naked costume pics porn
  • video
  • buy size petite womens jeans
  • video
  • adult asian girls iamges
  • plus size sexy farm girl costume
  • hardcore sex videos jizzonline
  • teen girls wallpaper border
  • sexy mature videos online
  • free online photos mature women sexy
  • video
  • Meet hot girls online
  • free online videos of oral sex
  • free porn online lesbians
  • free online hardcore lesbian romance novels
  • online gallery of russian teen girls
  • online mature hollywood movies
  • blowjob video online
  • vintage blonde hairy farmgirl
  • video
  • free teen girls fuckimg
  • watch ebony bbw sex porn online
  • video
  • asian black dating man online woman
  • pictures of sex online
  • college girls sexfor tallahassee sale
  • amateur porn threesome dvds for sale
  • video
  • online big dick in ass videos
  • buy porn movies and sex toys
  • hot sex videos free online
  • free online huge dildo fuck videos
  • free ebony porn movies online
  • girls in devil costumes pics
  • watch porn movies online
  • video
  • watch free erotic movie online
  • video
  • old buys young girls
  • free gamgbang anal sex
  • amateur girls videos free online
  • radioactive teens imgage gallery
  • girls geisha asian costume clearance
  • black petite womans jacket dresses sale
  • free online tight teen pussy videos
  • celeb free online video sex
  • erotic movie sales
  • free online erotic movie
  • love girls online porn
  • porn videos for sale
  • free online hardcore lesbian hentai
  • free online young teen sex videos
  • free sex mpg online videos
  • doctors orders sex videos
  • free online porn videos with chains
  • free online website ass pussy
  • dave price wife pictures
  • longest anal fucking video online
  • japanes online sex
  • video
  • video
  • online streaming sex vids x hamster
  • online videos anal plugs
  • online sex pictures
  • naked sales girl
  • japanese girls online
  • halloween mask hood black party costume
  • free fucking hardcore sex mgp movies
  • shemale online videos
  • video
  • video
  • blondie naked farmgirl
  • video
  • free online illegal porn movies
  • video
  • video
  • read hardcore porn online
  • teen online sex eduion
  • video
  • video
  • video
  • cheap girls black silver pagent dresses
  • video
  • deep throat the movie online
  • online sex moviesdownload
  • video
  • german news online topless girl
  • free online amiture sex videos
  • free online girl sex movies
  • video
  • video
  • sexy erotic costumes
  • buy black moon movie
  • free online erotic videos for couples
  • free online anime porn tube movies
  • free full length sex vids online
  • video
  • video
  • video
  • video
  • free online tiny teens videos
  • free online black anime porn
  • Katie price nude sex tape
  • video
  • cheap pussy paris
  • free ebony lesbian video online
  • free online cock orgasm denial video
  • sites to buy softcore sex movies
  • free online sex video indian
  • claudia price sex videos
  • stories short online romantic erotic sexy
  • video
  • video
  • california asian dreamgirls
  • sexy youmg couples handjob
  • video
  • cheap small unique gifts young girls
  • tight teen pussy videos online
  • sexy young elvis costume
  • Kate beckinsale naked video
  • little caprice handjob video
  • sex pics videos cheap looking secretary
  • hot lesbian sex online
  • katie price hardcore sex
  • young amateurs pics online
  • porn priceless ex girlfriend
  • free blowjob vids and pics online
  • sexy costa rica girls at beach
  • video
  • sex free japan online
  • video
  • video
  • cheap microsuede petite pants
  • Mood disorders in teens
  • free online ass gaping movies
  • anal free online porn first time
  • japan camgirl pussy
  • best online video porn site
  • watch free amateur sex videos online
  • black girls online message board
  • xxx online sex stores
  • video
  • free online simpsons porn vids
  • girls buying sex
  • free online oon sex vids
  • online video bouncing tits
  • free online shemale video sites
  • free online harcdcore sex black girls
  • free online desi sex videos
  • dreamgirls subliminal sex torrent
  • video
  • katie price black bikini
  • online secretary fuck videos
  • free online british porn videos
  • video
  • video
  • video
  • video
  • online school girls porn
  • dc comics supergirl teen costume
  • free hot shemale online videos
  • online videos butt plugsin use
  • free video of katie price naked
  • asian horror movies online
  • girls black and white sale oxfords
  • costume porn free pics
  • sex videos online paris hilton
  • watch free big tits videos online
  • throat disorders oral sex
  • video
  • facial videos online
  • free sex movies online tv
  • young teen porn online for free