Search code examples
androidandroid-layout

View wrap_content in not working in TableLayout


I add table rows with cells to a table dynamically. The rows and cells are added, but the text in the cells do not wrap. Part of code follows here:

Layout is as follows:

<TableLayout
          android:id="@+id/TableTheOpenQuestion"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginLeft="12dp"
          android:layout_marginTop="1dp"
          android:layout_marginRight="12dp"
          android:backgroundTint="@color/backgroundColor"
          android:visibility="gone"
          android:stretchColumns="*">
      </TableLayout>

And the corresponding Java file where I use the above layout is as follows:


      tableLayout = findViewById(R.id.TableTheOpenQuestion);
      TableRow tr = new TableRow(dContext);
      TableRow.LayoutParams params = new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, 1);
      params.setMargins(12, 0, 12, 0);
      tr.setLayoutParams(params);
      TableRow.LayoutParams cellParams = new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);

      TextView tv = new TextView(dContext);
      tv.setLayoutParams(cellParams);
      tv.setPadding(5, 10, 10, 10);
      tv.setText("A very long text.A very long text.A very long text.A very long text.A very long text.A very long text.A very long text.A very long text.");
      tr.addView(tv);

      //
      // Add the row to the table
      //
      tableLayout.addView(tr);

I have been searching a lot of similar questions, but nothing seems to work for me. All help greatly appreciated!


Solution

  • For the TextView, TableRow params should be as follows, instead of what you've written

    TableRow.LayoutParams params = new TableRow.LayoutParams(
                    0, // Width 0 to allow wrapping
                    TableRow.LayoutParams.WRAP_CONTENT, // Wrap content height
                    1.0f // Equal weight for each cell
            );
    

    And then you can assign the params to your TextView

    TextView textView = new TextView(context);
    textView.setText(text);
    textView.setLayoutParams(params);