简体   繁体   中英

Programmatically set margin for TableRow

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?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM