2011-01-02 14 views
15

Ho creato TableRows dinamicamente nel codice e voglio impostare i margini per questi TableRows.Programmare il margine per TableRow

mio TableRows creato come segue:

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

Come posso dinamicamente impostare i margini di questi?

risposta

61

È necessario impostare LayoutParam correttamente. Il margine è una proprietà di layout e non di TableRow, quindi è necessario impostare i margini desiderati in LayoutParams.

Heres un codice di esempio:

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

Ha funzionato! Tnx !!! – ofirbt

+4

Che ne dici di una visualizzazione testuale? setMargins undefined per textView. – Jaseem

+0

Non ha funzionato. Ma la risposta di @mik sotto funzionava, e avrebbe dovuto essere la risposta accettata – Zvi

7

Questo è il lavoro:

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

È necessario aggiungere la TableRow a TableLayout passando nuovamente i parametri di layout!

+1

Dovrebbe essere la risposta accettata. Senza l'ultima riga della risposta non funziona 'yourTableLayoutInstance.addView (tr, lp);'. – Zvi