我创建了一个包含五个表格行的表格。第一行是每个表的标题。 在接下来的四行中,每第二列 shell 代表一个图像和一个 TextView 。 我的问题是我的图像显示在行的中央。 如果我为图像的宽度添加一些布局参数,它就会消失。
我希望我的图片是左对齐的,所以它紧挨着我的第一列结束。
创建行:
for (int i = 0; i < 4; i++) {
TableRow tableRow = new TableRow(context);
for (int column = 1; column <= 8; column++) {
TextView textView = null;
if (column == 2) {
ImageView imgView = new ImageView(context);
imgView.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
tableRow.addView(imgView);
textView = new TextView(context);
textView.setGravity(LEFT);
} else {
textView = new TextView(context);
}
textView.setGravity(CENTER);
textView.setTextColor(WHITE);
tableRow.addView(textView);
}
tableLayout.addView(tableRow);
}
用数据更新表格:
for (int column = 0; column <= 7; column++) {
View child = tableRow.getChildAt(column);
if (child instanceof ImageView) {
ImageView flag = (ImageView) child;
flag.setImageResource(getFlagByClubName(group.getTeams().get(i).getClub()));
}
if (child instanceof TextView) {
TextView textView = (TextView) tableRow.getChildAt(column);
setContentInColumn(group.getTeams().get(i), column, textView);
}
}
最佳答案
您可以尝试将 imageview 和 textview 包装在相对布局中。请注意,我没有测试下面的代码,但它改编 self 的其他一些运行良好的代码。
RelativeLayout wrapper = new RelativeLayout(context);
// Create imageView params
RelativeLayout.LayoutParams imageParams;
imageParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// Create imageView
ImageView imageView = new ImageView(context);
imageView.setLayoutParams(imageParams);
imageView.setId(1);
// Create textView params
RelativeLayout.LayoutParams textParams;
textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
textParams.addRule(RelativeLayout.LEFT_OF, imageView.getId());
// Create textView
TextView textView = new TextView(context);
textView.setLayoutParams(textParams);
// Add to the wrapper
wrapper.addView(imageView);
wrapper.addView(textView);
然后只需将 wrapper
添加到您的表中:
tableRow.addView(wrapper);
关于android - 以编程方式设置 ImageView 的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346231/