2011-01-02 10 views
15

Tengo TableRows creado dinámicamente en el código y quiero establecer márgenes para estos TableRows.Margen establecido programáticamente para TableRow

Mi TableRows creado los siguientes:

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

¿Cómo se configura dinámicamente los márgenes de estos?

Respuesta

61

Debes configurar LayoutParams correctamente. El margen es una propiedad del diseño y no del TableRow, por lo que debe establecer los márgenes deseados en los LayoutParams.

Heres un ejemplo de código:

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

¡Funcionó! Tnx !!! – ofirbt

+4

¿Qué tal un textView? setMargins undefined para textView. – Jaseem

+0

No funcionó. Pero la respuesta de @mik a continuación funcionó, y debería haber sido la respuesta aceptada – Zvi

7

Esto está funcionando:

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

Es necesario añadir su TableRow a TableLayout pasando los parámetros de diseño de nuevo!

+1

Debería haber sido la respuesta aceptada. Sin la última línea en la respuesta, no funciona 'yourTableLayoutInstance.addView (tr, lp);'. – Zvi

Cuestiones relacionadas