我试过
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);
}
但是图片从未显示过。如果我将引力更改为CENTER_HORIZONTAL
,则它仅显示图片的一小部分。
使用xml创建表时,我认为它会自动水平对齐。我无法理解TableRow布局的工作原理。谁能让我对此有所了解?
答案 0 :(得分:3)
为每行添加额外的LinearLayout
解决了我的问题;)。前一行的对齐导致图片离开屏幕。
private void addSnapPictureRow(TableLayout table, Bitmap bitmap) {
/*
* 1st row = TextView (Check In)
*/
TableRow row = new TableRow(this);
LinearLayout outerLayout = new LinearLayout(this);
// add text
TextView text = new TextView(this);
text.setText("Snap Picture");
LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textLayoutParams.setMargins(100, 0, 0, 0);
// add picture
ImageView picture = new ImageView(this);
LinearLayout.LayoutParams pictureLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
picture.setImageResource(R.drawable.adium);
pictureLayoutParams.setMargins(20, 0, 0, 0);
outerLayout.addView(text, textLayoutParams);
outerLayout.addView(picture, pictureLayoutParams);
row.addView(outerLayout);
/*
* 2nd row = View (separator)
*/
TableRow separator = new TableRow(this);
View line = new View(this);
TableRow.LayoutParams separatorLayoutParams = new TableRow.LayoutParams(400, 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);
}