我使用的下面的代码:
private void addSnapPictureRow(TableLayout table, Bitmap bitmap) {
/*
* 1st row = TextView (Check In)
*/
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
// add text
TextView text = new TextView(this);
text.setText("Snap Picture");
TableRow.LayoutParams textLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
textLayoutParams.setMargins(100, 0, 0, 0);
row.addView(text, textLayoutParams);
// add picture
ImageView picture = new ImageView(this);
picture.setImageResource(R.drawable.adium);
row.addView(picture);
/*
* 2nd row = View (separator)
*/
TableRow separator = new TableRow(this);
View line = new View(this);
TableRow.LayoutParams separatorLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 1);
separatorLayoutParams.setMargins(100, 0, 0, 0);
line.setBackgroundColor(Color.BLUE);
separator.addView(line, separatorLayoutParams);
// add row to table
table.addView(row);
// add a separator
table.addView(separator);
}
但是图像并没有出现,如果我把 gravity 改成CENTER_HORIZONTAL,但是只显示图像的一部分:
当使用xml创建表格时,我以为它会自动的水平对齐。我不知道TableRow layout是如何运行。请大家指点一二。
ChatGPT尝试为您解答,仅供参考
使用表格布局 (TableLayout) 显示图像时,可能需要调整行 (TableRow) 中图像视图 (ImageView) 的布局参数。
您可以通过创建 TableRow.LayoutParams 并将其传递给 addView 方法来调整图像视图的布局。
例如,要将图像视图放在行的中间,您可以这样做:
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
row.addView(picture, layoutParams);
此外,如果要调整图像的大小,您可以使用 ImageView 的 setScaleType 方法。例如,要让图像填充整个视图,您可以这样做:
picture.setScaleType(ImageView.ScaleType.FIT_XY);
如果您只想显示图像的一部分,则可以使用 setCropToPadding 属性。例如:
picture.setCropToPadding(true);