Content not showing in dynamically created android TableLayout

吃可爱长大的小学妹 提交于 2019-12-01 12:53:07

Your TextViews are children of a TableRow so you should set an instance of TableRow.LayoutParams for the LayoutParams instead of the simple one(probably from the ViewGroup super class) that you currently use:

//...
        TextView tv = new TextView(this);
        tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT));
        tv.setText("text 1");
        tr.addView(tv);

        TextView tv1 = new TextView(this);
        tv1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT));
        tv1.setText("text 2");
        tr.addView(tv1);

        TextView tv2 = new TextView(this);
        tv2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT));
        tv2.setText("text 3");
        tr.addView(tv2);
//...

Try like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="350dp"
        android:layout_marginTop="10dp" android:stretchColumns="*" >
    </TableLayout>

    <Button
        android:id="@+id/BorrarPedido"
        android:layout_width="204dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Borrar Pedido" />

    <Button
        android:id="@+id/EnviarPedido"
        android:layout_width="204dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Enviar Pedido" />
</LinearLayout>


    TableLayout tblLayout = (TableLayout)findViewById(R.id.tableLayout1);

    TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);

    TableRow row = new TableRow(this);
    row.setBackgroundColor(Color.DKGRAY);
    tblLayout.addView(row, layoutParams);

    addToTableRow("Name", row, Color.WHITE);
    addToTableRow("Age", row, Color.WHITE);
    addToTableRow("Location", row, Color.WHITE);
  }

  private void addToTableRow(String str, TableRow row,int color) 
  {
    TextView t = new TextView(this);
    t.setTextColor(color);
    t.setText(str);
    row.addView(t);
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!