views:

34

answers:

1

Hi all,

I want to create say 5 different types of cells in table along with identifiers and load them appropriately as per the given data depending upon the type? Creating TableRow inside TableLayout seems to be one of the options but how to dynamically create the tableRows depending upon the type?

Thanx in advance.

A: 

Can you detect the type on execution time? If yes, it should be straight forward using a switch or an if else structure.

To inflate an XML resource on run time depending on the row type use:

((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layoutId, yourTableLayout, true);

Set the appropiate layoutId before inflating the resource and then proceed. The parameters yourTableLayout and true are just my guess, check the documentation at LayoutInflater and choose the inflate method that fits yout needs.

To create TableRows dynamically, this tutorial may help: Creating TableRow rows inside a TableLayout programatically

Basically:

1- Fetch TableLayout and create TableRow

// Get the TableLayout
TableLayout tl = (TableLayout) findViewById(R.id.maintable);

TableRow tr = new TableRow(this);
tr.setId(100+current);
tr.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));   

2- Create elements to add

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);

3- Add the TableRow to the TableLayout

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

Seems to be easy and fast, I haven't tested it tho.

Maragues
Since the tableRows are of different type [5 different types], the elements added are different. I want to save it in xml with some identifier and load the appropriate one at runtime. Is it possible?
neha
I've updated the answer, I hope that clarifies your question.
Maragues