Dynamically create an Android tablet

I want to dynamically add rows to a table. 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) relativeLayout.getChildAt(0);
                            textView.setText(string);
                            imageView= (ImageView) relativeLayout.getChildAt(1);
                            imageView.setBackgroundColor(R.color.blue);
                            tableRow.addView(relativeLayout);
                            tableLayout.addView(tableRow);
                        }

I created a line layout with a width of fill_parent, with text on the left to the left and with an image on the right to the right. However, when I run this program, the line width appears wrap_content instead of fill_parent with text overlapping the image. Please help. Thanks

+3
source share
1 answer

The first thing I notice is that you do not install 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 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 like to distract the creation of strings in their own method. for ease of use / reuse.

+1
source

Source: https://habr.com/ru/post/1767347/


All Articles