20

I have TableRows created dynamically in the code and I want to set margins for these TableRows.

My TableRows created as follow:

// Create a TableRow and give it an ID
        TableRow tr = new TableRow(this);       
        tr.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  
        Button btnManageGroupsSubscriptions = new Button(this);
        btnManageGroupsSubscriptions.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 40));

        tr.addView(btnManageGroupsSubscriptions);
        contactsManagementTable.addView(tr);

How do I dynamically set the margins for these?

Myles Gray
  • 8,711
  • 7
  • 48
  • 70
ofirbt
  • 1,846
  • 7
  • 26
  • 41

2 Answers2

73

You have to setup LayoutParams properly. Margin is a property of layout and not the TableRow , so you have to set the desired margins in the LayoutParams.

Heres a sample code:

TableRow tr = new TableRow(this);  
TableLayout.LayoutParams tableRowParams=
  new TableLayout.LayoutParams
  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);

int leftMargin=10;
int topMargin=2;
int rightMargin=10;
int bottomMargin=2;

tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

tr.setLayoutParams(tableRowParams);
Shardul
  • 27,760
  • 6
  • 37
  • 35
14

This is working:

TableRow tr = new TableRow(...);
TableLayout.LayoutParams lp = 
new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                             TableLayout.LayoutParams.WRAP_CONTENT);

lp.setMargins(10,10,10,10);             
tr.setLayoutParams(lp);

------

// the key is here!
yourTableLayoutInstance.addView(tr, lp);

You need to add your TableRow to TableLayout passing the layout parameters again!

ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89
  • 1
    Should have been the accepted answer. Without the last line in the answer it does not work 'yourTableLayoutInstance.addView(tr, lp);'. – Zvi Jul 16 '16 at 16:43