I am trying to add rows to a TableLayout that I define in an XML file. The XML file contains a header row for the table.
I can add new rows quite well using info from various tutorials but the code required for setting up the layout for the new rows is a horrendous mess and it seems like a pain in the ass to maintain whenever the layout for the header row changes.
Is it possible to create new rows to a TableLayout while still defining the row layout in XML? For example define a template row in XML, obtain a handle to it in code and then clone the template whenever I need it.
Or is the right way to do this somehow completely different?
Your proposed approach will work fine and it more or less matches the common pattern used when populating ListView items.
Define a layout that contains a single row. Obtain a
LayoutInflaterby usingLayoutInflater.from(myActivity). Use this inflater to create new rows using your layout like a template. Generally you will want to use the 3-argument form ofLayoutInflater#inflatepassingfalsefor the thirdattachToRootparameter.Let’s say you wanted to use a template layout with a label and a button in each item. It might look something like this: (Though yours would define your table rows instead.)
res/layout/item.xml:
Then at the point where you inflate: