2011-01-02 15 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を適切にセットアップする必要があります。余白はLayoutのプロパティであり、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はどうですか? 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

関連する問題