2010-09-30 56 views
3

我想動態添加行到tablelayout。這是我的代碼。動態創建tablelayout android

TableRow tableRow = null; 
TextView textView = null; 
ImageView imageView = null; 
TableLayout tableLayout = (TableLayout)findViewById(R.id.tableLayout); 
RelativeLayout relativeLayout = null; 
     for (String string: listOfStrings) { 
          tableRow = new TableRow(this); 
          relativeLayout = (RelativeLayout) View.inflate(this, 
            R.layout.row, null); 
          textView = (TextView) relativeLayout.getChildAt(0); 
          textView.setText(string); 
          imageView= (ImageView) relativeLayout.getChildAt(1); 
          imageView.setBackgroundColor(R.color.blue); 
          tableRow.addView(relativeLayout); 
          tableLayout.addView(tableRow); 
         } 

我已經創建了寬度FILL_PARENT一排佈局,TextView的在最左側和最右側的ImageView的。但是,當我運行這個程序時,行寬出現wrap_content而不是fill_parent與圖像重疊文本。請幫忙。謝謝

回答

1

我注意到的第一件事是在添加視圖時,您沒有設置任何LayoutParams。

TableRow tableRow = null; 
TextView textView = null; 
ImageView imageView = null; 
TableLayout tableLayout = (TableLayout)findViewById(R.id.tableLayout); 
RelativeLayout relativeLayout = null; 

for (String string: listOfStrings) 
{ 
    tableRow = new TableRow(this); 
    relativeLayout = (RelativeLayout) View.inflate(this, R.layout.row, null); 
    textView = (TextView) relativeLayout.getChildAt(0); 
    textView.setText(string); 
    imageView= (ImageView) relativeLayout.getChildAt(1); 
    imageView.setBackgroundColor(R.color.blue); 

    //Here's where I would add the parameters... 
    TableLayout.LayoutParams rlParams = new TableLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT); 
    tableRow.addView(relativeLayout, rlParams); 
    tableLayout.addView(tableRow); 
} 

實際上,我也會將行的創建抽象爲他們自己的方法。以簡化使用/重複使用。