动态添加的ImageView为tablerow动态、ImageView、tablerow

2023-09-06 17:46:33 作者:矫情&滚

我在我的XML一个TableLayout,我想动态添加的TableRow与ImageView的该TableLayout。我到目前为止是这样的:

I have a TableLayout in my XML, and I'd like to dynamically add a TableRow with an ImageView to that TableLayout. What I have so far is this:

TableRow tr = new TableRow(this);
ImageView imgView = new ImageView(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                            LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT);
imgView.setLayoutParams(lp);
imgView.setImageDrawable(getResources().getDrawable(R.drawable.icon_test));
tr.addView(imgView);
tlCollection.addView(tr);

我是什么做错了吗?如果我想一个TextView添加到相同的TableRow,它的工作原理,但添加的ImageView不起作用。

What am I doing wrong? If I want to add a Textview to the same TableRow, it works, but adding an ImageView doesn't work..

在code添加一个TextView:

The code for adding a TextView:

TextView myTextView = new TextView(this);

myTextView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.WRAP_CONTENT));
myTextView.setText("Test");
tr.addView(myTextView);

任何想法?

推荐答案

我固定它,使用LayoutInflater:

I fixed it, using an LayoutInflater:

LayoutInflater inflater = getLayoutInflater();

TableRow row = (TableRow)inflater.inflate(R.layout.collection_row, tlCollection, false);

//fill textview
TextView content = (TextView)row.findViewById(R.id.txtCollection);
content.setText("Test");

//fill imageview
ImageView myImgView = ImageView)row.findViewById(R.id.imgCollection);           
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.my_icon));

//add row to tablelayout
tlCollection.addView(row);