2012-01-31 71 views
12

我有這些我動態生成的文本字段。但我似乎無法爲它們設置佈局參數。請告訴我我做錯了什麼。如何在Android中動態設置佈局參數?

我能夠生成沒有佈局參數的字段。但是,如果我使用LayoutParams,它甚至不會生成。

代碼:

TableLayout table = (TableLayout) findViewById(R.id.TableLayout1); 

TableRow tr = new TableRow(this); 
LinearLayout.LayoutParams trparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
tr.setLayoutParams(trparams); 

cg[i] = new EditText(this); 
weight[i] = new EditText(this); 
cg[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 
weight[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); 

//Here's where it goes wrong. By adding fieldparams, the text field doesn't even get generated. 
LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(10, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); 
tr.addView(cg[i], fieldparams); 
tr.addView(weight[i], fieldparams); 

table.addView(tr); 
+6

是不是你在一個tablerow上使用linearlayout.layoutparams?它不適合tablerow.layoutparams – Amit 2012-01-31 12:45:29

+1

好評...但小改正Amit.it將TableLayout不TableRow – Sameer 2012-01-31 13:25:03

回答

14

您要添加錶行成表,以便使用TableLayout.LayoutParams,而不是我們使用LayoutParam根據父LinearLayout.LayoutParams。正如我們在其中要添加

6

,你必須使用TableRow.LayoutParams代替LinearLayout.LayoutParams

替換代碼

LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(10, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); 

用下面的代碼。

TableRow.LayoutParams fieldparams = new TableRow.LayoutParams(10, TableRow.LayoutParams.WRAP_CONTENT, 1.0f); 

它的工作正常。讓我知道發生了什麼事。 :-)