2013-03-17 93 views
0

爲了標籤的目的,我在一個FrameLayout中有一個LinearLayout。我試圖在代碼中將TableRow添加到LinearLayout中。Android以編程方式向一個TableRow添加多個TextView

LinearLayout testLayout = (LinearLayout)findViewById(R.id.testLayout); 
TableRow tableRow = new TableRow(this); 
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); 

這得到我的LinearLayout並創建一個TableRow到我想要的規格。我知道這部分正在工作。

TextView textOne = new TextView(this); 
textOne.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
textOne.setText("One"); 

TextView textTwo = new TextView(this); 
textTwo.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
textTwo.setText("Two"); 

這裏我讓我的兩個TextViews沒有問題。

tableRow.addView(textOne); 
tableRow.addView(textTwo); 
testLayout.addView(tableRow, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 

這裏是我認爲一切都出錯的地方。會發生什麼,它只顯示textTwo。我不知道爲什麼它不會像XML中的正常TableRow那樣顯示它們。我再說一遍,這必須在代碼中完成。 請幫忙,謝謝。

回答

0

你有進口這import android.widget.TableRow.LayoutParams

下面的代碼對我的作品

TableLayout tl = (TableLayout) findViewById(R.id.spreadsheet); 
    TableRow tr = new TableRow(this); 
    LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
    tr.setLayoutParams(lp); 

    TextView tvLeft = new TextView(this); 
    tvLeft.setLayoutParams(lp); 
    tvLeft.setBackgroundColor(Color.WHITE); 
    tvLeft.setText("OMG"); 
    TextView tvCenter = new TextView(this); 
    tvCenter.setLayoutParams(lp); 
    tvCenter.setBackgroundColor(Color.WHITE); 
    tvCenter.setText("It"); 
    TextView tvRight = new TextView(this); 
    tvRight.setLayoutParams(lp); 
    tvRight.setBackgroundColor(Color.WHITE); 
    tvRight.setText("WORKED!!!"); 

    tr.addView(tvLeft); 
    tr.addView(tvCenter); 
    tr.addView(tvRight); 

    tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

    tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); 
0

我認爲要動態創建的TextView和should're得到錯誤 「removeView()父。」這是一個很好的解決方案:

TableView tlSkills = (TableView) findViewById(R.id.myTableView); 
if(listSkills.size() > 0) { 
    TableRow tableRow = new TableRow(getContext()); 

    int i = 0; 
    for (Skills s : listSkills) { 
    TextView textView = new TextView(getContext()); 
    textView.setText("" + s.getName()); 

    tableRow.addView(textView); 

    if(i > 0) { 
      tlSkills.removeView(tableRow);//this is to avoid the error I mentioned above. 
    } 

    tlSkills.addView(tableRow); 

    i++; 
    } 
} 
相關問題