2010-09-30 57 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); 
} 

实际上,我也会将行的创建抽象为他们自己的方法。以简化使用/重复使用。