Michael Manley Michael Manley - 4 months ago 16
Android Question

What is this Android Snippet doing?

EDIT** Figured out my own answers except for my major question as follows:

TableLayout tableLayout = new TableLayout(this);

TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 1; j <= courseHoleCount; j++) {
**TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));**
tv.setBackgroundResource(R.drawable.cell_shape);
tv.setTextSize(30);
tv.setPadding(5, 5, 5, 5);
tv.setText(String.valueOf(players[i-1].getScore()[j-1]));// (-1) because j = 1 and not 0.
row.addView(tv);
}
tableLayout.addView(row);


linearLayout.addView(tableLayout);


In the above code snippet, what does this do and what/why are TableRow.Layout params being added to a text view layout param?

tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));

Answer

TableRow.LayoutParams are being used because tv is a child of row which is a TableRow. If you look at the Android API reference, it says

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged.

And the two parameters for the LayoutParams constructor are used to set the width and height of tv. Since both width and height is set to WRAP_CONTENT, the size of tv will be big enough to enclose its content (plus padding).