Android-Dynamic TableRow 仅添加 1 行

Android-Dynamic TableRow Adding Only 1 Row

我已经在 xml 中创建了一个表格布局,但正在动态添加表格行。我以为我有它,但是执行时我只添加了第一个表格行。

TableRow componentDTableRow() {
    Log.d("ADD TO D", "TABLE D");
    TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    params.setMargins(2, 2, 2, 2);
    TableRow newRow=null;


    for (int x = 0; x < 10; x++) {
        newRow = new TableRow(this);
        for (int y = 0; y < 10; y++) {
            TextView textViewD = new TextView(this);
            textViewD.setTextSize(18);
            textViewD.setWidth(400);
            textViewD.setTextColor(Color.BLACK);
            String test = "TEST";
            textViewD.setText(test);
            newRow.addView(textViewD, params);

        }

    }

    return newRow;

}

部分xml:

<ScrollView
    android:id="@+id/svD"
    style="@android:style/Widget.ScrollView"
    android:layout_width="791dp"
    android:layout_height="272dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/vsC"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/hsvB">

    <HorizontalScrollView
        android:id="@+id/hsvD"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableLayout
            android:id="@+id/tableD"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">


        </TableLayout>
    </HorizontalScrollView>
</ScrollView>

scollview 处于约束布局中。 我认为这是循环中的某些东西,但我无法确定是什么。任何帮助表示赞赏。

您只是覆盖了 newRow 10 次:

for (int x = 0; x < 10; x++) {
    newRow = new TableRow(this);
    for (int y = 0; y < 10; y++) {
        //etc
    }

    // Here you need to do something with `newRow`, perhaps add it to your table
}

1.add TableLayout

2.for循环添加newRow

3.TableLayout addView 在for循环中

你可以这样做。

Log.d("ADD TO D", "TABLE D");
// add TableLayout
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableD);
//  add TableRow.LayoutParams
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    params.setMargins(2, 2, 2, 2);
TableRow newRow = null;
// for loop to add newRow
    for (int x = 0; x < 10; x++) {
    newRow = new TableRow(this);
    for (int y = 0; y < 10; y++) {
        TextView textViewD = new TextView(this);
        textViewD.setTextSize(18);
        textViewD.setWidth(400);
        textViewD.setTextColor(Color.BLACK);
        String test = "TEST";
        textViewD.setText(test);
        newRow.addView(textViewD, params);
    }
    //  tableLayout addView
    tableLayout.addView(newRow);
}