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?
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.
getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView. setLayoutParams(layoutParams);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With