Android: layout_weight does not work when it is installed programmatically

I have a problem when I programmatically set TableRow layout_weight . The following code is a TableLayout inflated table_body element:

 <TableLayout android:layout_width="match_parent" android:layout_height="0px" android:layout_weight="1" android:weightSum="1"> <TableLayout> 

I want to display only 10 rows in a TableLayout .. and for this I add TableRow elements programmatically using this code:

 while(i<10){ TableRow row = (TableRow) ((Activity) context).getLayoutInflater(). inflate(R.layout.body_row, table_body, false); TableRow.LayoutParams row_params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.1f); table_body.addView(row, row_params); i++; } 

body_row.xml has the following code:

 <TableRow> <TextView android:text="row1" android:layout_width="match_parent" android:layout_height="match_parent"/> </TableRow> 

With this code, TableLayout not divided into 10 equal spaces (as we would like), but the rows only carry their contents with a space between the end of the last row and the end of TableLayout .. What am I doing wrong? Thanks!!

+4
source share
1 answer

To make the weight mechanism work, you must use the correct LayoutParams for your inflated TableRow widgets. Since the parent element of TableRow is TableLayout , then you need to use TableLayout.LayoutParams :

 TableLayout.LayoutParams row_params = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.1f); table_body.addView(row, row_params); 
+9
source

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


All Articles