Mudasser Hassan
Mudasser Hassan

Reputation: 726

Android: Programmatically Setting width of Child View using Percentage

I've read this article:

Setting width of Child View using Percentage

So far it works great if we set the weight and width in XML but I want to do it programmatically. I've a table in my layout (XML) and I am adding rows to it programmatically. In each row, I am adding 2 Text Views. I tried doing like this:

TableLayout tl = (TableLayout)findViewById(R.id.myTable);
for(int i = 0; i < nl.getLength(); i++){
            NamedNodeMap np = nl.item(i).getAttributes();
                TableRow trDetails = new TableRow(this);
                trDetails.setBackgroundColor(Color.BLACK);
                TextView tvInfo = new TextView(this);
                tvInfo.setTextColor(Color.WHITE);
                tvInfo.setGravity(Gravity.LEFT);
                tvInfo.setPadding(3, 3, 3, 3);
                tvInfo.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);

                tvInfo.setText("info");

                TextView tvDetails = new TextView(this);
                tvDetails.setTextColor(Color.WHITE);
                tvDetails.setGravity(Gravity.LEFT);
                tvDetails.setPadding(3, 3, 3, 3);
                tvDetails.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
                tvDetails.setText(np.getNamedItem("d").getNodeValue());

                trDetails.addView(tvInfo, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50f));
                trDetails.addView(tvDetails, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50f));

                tl.addView(trDetails,new TableLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));
}

but with no luck, it shows blank screen but if I do it in XML then it shows perfectly. Please help me sorting out this issue where I am doing wrong?

Thanks

Upvotes: 2

Views: 3499

Answers (1)

Ron
Ron

Reputation: 24235

You should use TableRow.LayoutParams and not Linearlayout.LayoutParams

trDetails.addView(tvInfo, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50));
trDetails.addView(tvDetails, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50));

Upvotes: 8

Related Questions