开发者

Dynamic creation of tablelayout android

I want to add rows to a tablelayout dynamically. This is my code.

 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) relative开发者_JS百科Layout.getChildAt(0);
                            textView.setText(string);
                            imageView= (ImageView) relativeLayout.getChildAt(1);
                            imageView.setBackgroundColor(R.color.blue);
                            tableRow.addView(relativeLayout);
                            tableLayout.addView(tableRow);
                        }

I have created a row layout with width fill_parent, with textView on left most side and an imageView on right most side. However when I run this program the row width appears wrap_content instead of fill_parent with image overlapping text. Please help. Thanks


The first thing I notice is that you aren't setting any LayoutParams when adding your views.

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);
}

In practice, I would also abstract the creation of the rows into their own method. to simplify use/reuse.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜