2011-01-02 10 views
15

나는 코드에서 동적으로 생성 된 TableRows을 가지고 있으며 이것들에 대한 여백을 설정하려고합니다. TableRows. 프로그래밍 방식으로 TableRow의 여백 설정

TableRows 다음과 같이 생성 :

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

가 어떻게 동적으로 이들에 대한 여백을 설정합니까?

답변

61

LayoutParams를 올바르게 설정해야합니다. 여백은 TableRow가 아닌 ​​레이아웃의 속성이므로 LayoutParams에서 원하는 여백을 설정해야합니다.

Heres는 샘플 코드 :

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

Worked! Tnx !!! – ofirbt

+4

텍스트 뷰는 어떻습니까? textView에 대해 setMargins가 정의되지 않았습니다. – Jaseem

+0

작동하지 않았습니다. 하지만 아래의 @mik의 대답이 효과가 있었고 받아 들여진 대답이었을 것입니다. – Zvi

7

이이 작동 :

당신은 TableLayout을 레이아웃 매개 변수를 다시 전달에 TableRow를 추가 할 필요가
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); 

!

+1

받아 들여진 대답이었을 것입니다. 대답의 마지막 줄이 없으면 'yourTableLayoutInstance.addView (tr, lp);'가 작동하지 않습니다. – Zvi

관련 문제