ImageView拉伸表格单元格内的宽度

时间:2016-02-09 14:45:58

标签: android android-layout

我正在使用不同的细胞计数创建一个TableRow(在运行时)。所有颜色均匀地拉伸以填满桌子,这很好。 问题是在每个单元格内部都有一个ImageView,它被拉伸到表格单元格的大小,我无法设置为该imageview的最大宽度值。 这是添加imageview的代码:

imgV = new ImageView(getBaseContext());
                imgV.setLayoutParams(new TableRow.LayoutParams(1, TableRow.LayoutParams.WRAP_CONTENT, 1));
                //imgV.setMaxWidth(cellWidth/2);
                imgV.setMaxWidth(maxImgViewWidth);
                //imgV.getLayoutParams().width = maxImgViewWidth ;

                tv.setPadding(5, 0, 5, 30);
                imgV.setBackgroundResource(smiley1Id);
                trIconsRow.addView(imgV);

这里是trIconsRow配置:

<TableLayout
                android:layout_width="match_parent"
                android:stretchColumns="*"
                android:id="@+id/ansTable"
                android:layout_marginTop="10dip"
                android:layout_height="wrap_content">
                <TableRow
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/tRowIcons"
                    android:layout_marginBottom="30dip"
                    android:gravity="center"
                    android:layout_gravity="center_horizontal">
                </TableRow></TableLayout>

我在这里错过了什么?

2 个答案:

答案 0 :(得分:0)

android:adjustViewBounds="true"或使用代码致电ImageView#setAdjustViewBounds(boolean).

答案 1 :(得分:0)

确定。所以我所做的是添加一个线性布局,它将包装imageview,并将充当表格单元格和imageview之间的“中介”:

LinearLayout ll = new LinearLayout(getBaseContext()) ;
                ll.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.WRAP_CONTENT, 1));
                ll.setGravity(Gravity.CENTER);
                ll.addView(imgV);
                trIconsRow.addView(ll);