Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: layout_weight not working when it is set programmatically

I have a problem when I set the TableRow layout_weight programmatically. Following code is the TableLayout inflated in 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 TableLayout.. and to do this i add TableRow elements programmatically using this is the 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 this code:

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

With this code TableLayout is not divided in 10 equal space (as I'd want) but rows only wrap their content with the result of blank space between the end of last row and the end of the TableLayout.. What I'm doing wrong? Thank you!!

like image 558
user1709805 Avatar asked Dec 27 '22 14:12

user1709805


1 Answers

To make the weight mechanism work you need to use the proper LayoutParams for your inflated TableRow widgets. As the parent of TableRow is a TableLayout then you need to use the TableLayout.LayoutParams:

TableLayout.LayoutParams row_params = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.1f);
table_body.addView(row, row_params);
like image 191
user Avatar answered Dec 29 '22 04:12

user