0

我有一系列按钮要添加到 TableLayout 中的不同行。每个按钮需要有不同的宽度。但是,最终将每个按钮的宽度设置为等于具有最大宽度的按钮。有人可以让我知道如何解决这个问题吗?

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

            <TableRow
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <TextView
                    android:id="@+id/cat"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:textSize="12sp"
                    android:textStyle="bold"
                    android:typeface="serif" >
                </TextView>

                <TextView
                    android:id="@+id/num_high"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:textSize="12sp"
                    android:textStyle="bold"
                    android:typeface="serif" >
                </TextView>
            </TableRow>
        </TableLayout>

Java代码:

    for (int i =0; i< 5; ++i){
        TableRow row = new TableRow(this);
        TextView t1 = new TextView(this);
        t1.setText("cat: ");
        t1.setTextSize(12);
        row.addView(t1);
        Button b1 = new Button(this);

        b1.setText(numHighRisk.toString());
        b1.setTextSize(12);
        b1.setPadding(0, 0, 0, 0);
        row.addView(b1);
        int width;
        if (i > 2)
            width = 20;
        else
            width = 40;
        int heightDp = (int) (25 * scale + 0.5f);
        int widthDp = (int) (width * scale + 0.5f);


        ViewGroup.LayoutParams params = b1.getLayoutParams();
        params.height = heightDp;
        params.width = widthDp;
        b1.setLayoutParams(params);

            TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
        table.addView(row,rowParams);
    }

(使用此代码每个按钮具有相同的宽度)

4

2 回答 2

1

是的,在表格布局中,所有项目都将具有相同的大小以使它们正确对齐,您可以做一件事,尝试为您的按钮提供边距,以便它们的大小会减小,不同按钮的边距不同。例如,

 android:layout_marginLeft="40dp"
 android:layout_marginRight="40dp"
于 2013-05-14T05:13:22.077 回答
0

通过一些实验,我能够通过首先将每个按钮添加到 FrameLayout 然后将 FrameLayout 添加到行来实现不同的宽度。

于 2013-05-15T13:08:53.043 回答