2

I have a general question regarding Android's separation of layouts into layout.xml files:

My app needs to display a table where the number of rows and columns varies at runtime. So far I did the layout up to the TableView in the corresponding layout/....xml file and then I added TableRow-s and cells (TextView) to the table at runtime as needed. The drawback of adding rows and cell programmatically is, that one can not really change the design later (e.g. changing colors or margins for the cells) without later code modification.

What I would this like to do is to add a single row to the table and a single cell to the row in the layout file and then use these as a "pattern" or templates to generate all the actual table's rows and cells. This would allow to specify colors and other parameters in the layout.xml file (and thus also be able to change them later without code change) but still allow for an arbitrary number of columns and cells.

However, I found no "copy"-constructor or "duplicate"-method in Views. How can one achieve this? What is the suggested method to create lists or tables from a single "example" or template element? Or is there another method to achieve what I want?

Hope I could make myself clear... Michael

mmo
  • 3,897
  • 11
  • 42
  • 63

1 Answers1

8

Generally with a TableLayout or ListView, you create a layout xml file for the row and then inflate it for each instance programmatically.

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

TableRow rowView = (TableRow)inflater.inflate(R.layout.my_row, null);
table.addRow(rowView);
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
  • OK - thanks! That must be the piece that I was missing. Does one need to create an individual new file for each of these objects? I.e. do I then need a file for the TableRow and another for the cell? And if I have different cell types (say text and dates) do then need an individual file for each? Or can I somehow put all these into a single file? I am asking because the first approach seems to lead to an avalanche of layout files (I have about 15 different cell types) so i am a bit worried to have to maintain all these files... – mmo Sep 07 '10 at 22:20
  • Typically I've had a file for each row, where each row in the table has the same set of cell types. Basically you just need to think about the largest component that is can always be inflated together. Also, have you looked at android styles? If the only goal is to style a textbox differently, then that might be what you need: http://developer.android.com/guide/topics/ui/themes.html – Cheryl Simon Sep 07 '10 at 22:38