Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set margin for TableRow

Tags:

android

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?

like image 752
ofirbt Avatar asked Jan 02 '11 07:01

ofirbt


People also ask

How do you set margin top programmatically?

Set LayoutParams to the view. To set margin to the view create LayoutParams instance, and set margin to the view. LinearLayout. LayoutParams layoutParams = new LinearLayout.

How do I set margins to recyclerView programmatically?

getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView. setLayoutParams(layoutParams);


2 Answers

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);
like image 189
Shardul Avatar answered Oct 24 '22 22:10

Shardul


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!

like image 41
ʞᴉɯ Avatar answered Oct 24 '22 22:10

ʞᴉɯ