【问题标题】:Incorrect Android Button Width in TableLayoutTableLayout 中的 Android 按钮宽度不正确
【发布时间】:2013-05-15 21:08:53
【问题描述】:

我有一系列按钮要添加到 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);
    }

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

【问题讨论】:

    标签: android android-button android-tablelayout


    【解决方案1】:

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

     android:layout_marginLeft="40dp"
     android:layout_marginRight="40dp"
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-15
        • 2013-08-16
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 2011-09-09
        • 2015-04-22
        相关资源
        最近更新 更多