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. kirit
    December 30, 2013 at 07:50

    Really very helpful

Leave a comment

Standard Login

Options:

Colors

  • does d cause impotence
  • bid
  • cold sore dose
  • krymas kaina
  • dosage for a dog
  • and
  • difference between
  • msds tablets
  • ds
  • contro i pidocchi
  • hct tab 32-12.5
  • lek
  • timberland white
  • buy uk
  • low dose hormonal acne
  • dosage kids
  • ds missed dose
  • malarone pregnancy
  • therapeutic serum level range
  • tmj pain
  • kegunaan
  • 30 mg 14 tablet
  • starter pack dosage
  • can you take and together
  • patient information sheet
  • first day taking
  • not working
  • tablets
  • side effects increased appetite
  • fruit juice commercial
  • normal dose of for bladder infection
  • achilles heel
  • bill kaulitz overdose
  • band russia
  • teratogenic effects
  • can i take and advil
  • will raise my blood pressure
  • skin side effects
  • and at same time
  • generation kennett square
  • chlamydia pneumoniae
  • 5 follicules
  • for withdrawal from opiates
  • can you take vitamin b while
  • used high fsh levels
  • vs zoloft for anxiety
  • dosage
  • and lupus
  • ampollas novartis
  • quickly does work
  • cream ebay
  • alcohol detox
  • banda cristiana
  • dosages available
  • calcium channel blockers
  • drug interaction
  • once a day
  • a inne leki
  • zoloft vs social anxiety
  • and bipolar
  • not effective 2009
  • taking provera with
  • when doesn't work
  • for severe depression
  • o que A
  • dog
  • product information australia
  • used for opiate withdrawal
  • reviews side effects
  • can u smoke weed while on
  • relief uk
  • contre indication
  • vitamin c
  • fast oral jelly
  • ad anti-dandruff shampoo 7 oz
  • menopause symptoms
  • odt kit orange
  • taking
  • source
  • and uterine lining thin
  • generic
  • vs
  • gonal f iui
  • keramag nr. 1 flachspA?l-wc wandhAngend
  • twitter
  • mechanism of action
  • launch date
  • can you take tums
  • relprevv pharmacokinetics
  • relief mr spc
  • accidentally took 1200 mg of
  • patient assistance form
  • can you take same time
  • cheap
  • ec 500
  • chances of twins on 100mg
  • what is the maximum daily dose of
  • mania
  • pregnancy calculator using
  • para sirve d
  • como age o no aborto
  • canadian pharmacy no prescription
  • can i mix and allegra
  • pomata costo
  • missed pill
  • drug manufacturer
  • taking after ectopic
  • liquid taste
  • 2 months in
  • side effects liver
  • for pcos side effects
  • treatment for osteoarthritis
  • success stories
  • for uti prophylaxis
  • hct urination
  • can take nattokinase
  • correction albumin calculator
  • deaths children
  • birth control acne
  • e trittico
  • discontinuation symptoms
  • informacion en espanol
  • max dose consta
  • bula composiAA?o
  • rash sun
  • technology ga
  • about medication
  • used for chlamydia
  • chemical structure
  • 4 weeks on
  • vs stroke prevention
  • buy no prescription
  • 1 por dia
  • frova
  • use 2 jelly intercourse
  • side effects stroke
  • 3mg
  • to treat uti in men
  • direct branford ct
  • inr levels
  • side effects stopping suddenly
  • cold medicine while
  • 5 mg
  • can i take extra to lose weight
  • will show up on a drug test
  • taking together
  • rapaflo and the same
  • generic release date november
  • 40 mg
  • walmart pharmacy generic
  • combined with iui success rates
  • ambien interaction
  • withdrawal---headaches
  • eltroxin
  • thyroid disease
  • in early pregnancy
  • 0.25mg
  • active ingredient
  • contraindications
  • as a histamine blocker
  • switching
  • can you drink beer while on
  • starter pack dosage
  • menstrual cramps
  • m aventis
  • samples for physicians
  • coupon
  • when is going generic in usa
  • herpes transmission study
  • can you take together
  • severe constipation
  • are and the same
  • difference between and
  • westcort
  • simplex 1 herpes
  • and provera for infertility
  • chlamydia pneumoniae
  • brain zaps withdrawal
  • and interaction
  • otc twice a day
  • a xyzal
  • buy from india
  • buy vancouver bc
  • side effects pregnant women
  • too much dry mouth
  • will show up drug test
  • la 4mg capsules
  • memory loss
  • does cause night sweats
  • vs
  • hcg pct
  • liquid dosage for children
  • rebate
  • aumenta a prolactina
  • alternatives
  • my yahoo account sending spam
  • peanut allergy
  • prn
  • para que sirve el tabletas
  • herpes genitale e
  • high blood pressure tablets
  • tinea versicolor treatment
  • through iv
  • can you take while your pregnant
  • 20 mg price cvs
  • vs
  • adhd treatment
  • why doesn't work for some men
  • package insert
  • herpes genitalis
  • irregular heartbeat
  • 6 mp and
  • trip report
  • autism side effects
  • for a 6 year old
  • sublingual canada
  • planters warts
  • starter kit orange
  • what is drug
  • tablets sale
  • mixing and poppers
  • does have a generic brand
  • 70 mg
  • doesn't work
  • pronunciation
  • dosage for ibs
  • no side effects
  • clonazepam and combination
  • dosage 0.5mg
  • cheaper than
  • e gh
  • difference between ds septra ds
  • daily vs 36 hour
  • ds side effects in children
  • will cause diarrhea
  • results 3 months
  • versus
  • interaction between benadryl
  • symptoms of pregnancy on
  • can you take with
  • cheapest
  • syrup
  • and for pct
  • questions
  • buy online
  • antibiotic cost
  • indications and usage
  • chloride vs. la
  • children's suspension
  • libido cure
  • signs and symptoms of high level
  • most effective way use
  • krople ulotka dawkowanie
  • price for 10mg
  • uses and side effects
  • vitamin e capsules
  • ac 120 mg
  • alternative cat bite
  • side effects sun exposure
  • equivalent dose
  • made my headache worse
  • for pneumonia in children
  • can take oxycodone
  • is it safe to take benadryl with
  • information birth control pill
  • unterschied
  • que es el medicamento
  • taking later than day 5
  • conversion
  • and together
  • leg edema
  • snorting
  • tac dung thuoc
  • for acne does it work
  • and weight gain
  • cure
  • e sport
  • sore throat after
  • neuroleptic malignant
  • syrup
  • para que mas sirve el
  • dosage mims
  • blurred vision
  • vs anyone
  • prix 20 mg
  • reverse hair loss
  • janssen pharmaceutical
  • 12.5 mg tablets
  • generic ingredients
  • buy uk
  • zombie
  • que es 0.5 mg
  • online canada
  • do people take to get high
  • hair loss
  • herbal 8000 mg
  • slow release
  • taking for allergies
  • 200mg capsules
  • side effects 10 20 mg
  • does snorting make you high
  • hot water cylinder
  • j code for
  • express tabletki
  • is a psychotropic drug
  • diarrhea
  • for meningitis exposure
  • comparison
  • is or or best
  • bad dreams
  • pharmacological classification
  • dopo quanto tempo funziona
  • fracture hip
  • antibiotics for sinus infection
  • withdrawal nausea
  • back pain
  • for e coli diarrhea
  • when will patent expire
  • better than
  • exercise after
  • nausea after
  • cream webmd
  • how long to cure chlamydia
  • xanax
  • in pregnancy first trimester
  • perianal fistula
  • a nurofen
  • como se toma la pastilla para abortar
  • cheap canada free shipping
  • turmeric
  • used to treat fibromyalgia
  • can you buy chemist australia
  • versus
  • and bipolar
  • dosierung kinder
  • 10 mg enough
  • will feel better
  • and together
  • withdrawal symptoms how long
  • patient education
  • cost uk
  • m cmi
  • lethal dose
  • missed dose monthly
  • adverse side effects
  • 6315540691
  • for children
  • and alcohol interaction
  • ventures company llc
  • joint pain knees
  • pediatric dosing
  • white stool
  • and
  • versus
  • versus zoloft
  • ditropan vs
  • serophene over counter
  • pediatric dosing
  • 16 mg astrazeneca
  • medication for bipolar
  • high blood pressure medication
  • y cerveza
  • quantidade de berotec e para nebulizaAA?o
  • and azor
  • nuclear pa
  • usar 5 meses
  • transsexual
  • and alcohol interaction
  • manufacturer
  • aspirin half life
  • dementia
  • long term effects taking
  • medicine side effects
  • can take 1600 mg
  • vs
  • reviews side effects
  • 4 refundowany
  • gel drug class
  • suspension stability
  • sweating side effect
  • 9.5 mg
  • side effects weight
  • via g-tube
  • 300 g
  • success stories
  • what is 200mg capsules used for
  • effects smoking
  • conflitto tra e turchia
  • topical
  • and
  • jaundice
  • i dojenje
  • bijsluiter gsk
  • withdrawal symptoms
  • shampoo side effects men
  • hep c
  • e ipertensione
  • weight loss side effects
  • after a stroke
  • does cure stomach ulcers