2009-10-07 57 views
23

我試圖以編程方式創建TableLayout。它只是不會工作。儘管xml文件中的佈局相同。這是我的:以編程方式創建TableLayout

public class MyTable extends TableLayout 
{ 
    public MyTable(Context context) { 
     super(context); 

     setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
     TableRow row = new TableRow(context); 
     row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

     Button b = new Button(getContext()); 
     b.setText("hello"); 
     b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); 
     row.addView(b); 
     addView(row) 
    } 
} 

... 

// In main activity: 
MyTable table = new MyTable(this); 
mainLayout.addView(table); 

當我運行這個,我沒有崩潰,但沒有出現。如果我擺脫了TableRow實例,至少該按鈕確實顯示爲TableLayout的直接子節點。我究竟做錯了什麼?

回答

6

事實證明,我需要指定TableRowLayout,TableLayout等佈局參數,否則表不會顯示!

+2

您可以發佈您的代碼的解決方案?看起來你已經在上面這樣做了。 – Atma 2011-08-29 21:19:26

+3

謝謝! @Atma TableRows應該使用TableLayout.LayoutParams,而TableRows中的視圖應該使用TableRow.LayoutParams。 :) – Brayden 2012-05-15 15:03:28

+0

可怕,你需要明確這樣做,但它對我來說,謝謝! – 2013-03-18 19:01:41

0

對我來說,得到我的我不得不打電話addContentView()

29

只是爲了讓答案更加明確:

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); 
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); 

TableLayout tableLayout = new TableLayout(context); 
tableLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// assuming the parent view is a LinearLayout 

TableRow tableRow = new TableRow(context); 
tableRow.setLayoutParams(tableParams);// TableLayout is the parent view 

TextView textView = new TextView(context); 
textView.setLayoutParams(rowParams);// TableRow is the parent view 

tableRow.addView(textView); 

說明
當你調用setLayoutParams,你應該通過父視圖

+3

不應該是tableRow.setLayoutParams(rowParams)? – Leon 2015-11-09 11:18:06

+0

救生員獎去@Gigori A.和mark。 Gigori A.爲這個答案並且標記爲他自己的答覆。 – 2016-05-14 10:48:45

+0

偉大而有益的解決方案。作爲附註,您應該在將行添加到文本視圖之前將行添加到表中。 tableLayout.addView(的TableRow); – 2016-10-20 03:58:34

0

你的問題是在這條線:

b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); 

您需要更改LayoutParamsTableRow.LayoutParams

b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));