以编程方式设置ImageView的对齐方式

时间:2014-06-21 22:00:03

标签: android alignment android-imageview android-tablelayout

我创建了一个包含五个表行的表。第一行是每个表的标题。 在以下四行中,每个第二列shell表示图像和文本视图。 我的问题是我的图像显示在行的中心。 如果我为图像的宽度添加一些layoutparams,它就会消失。

我想要保留我的照片的对齐方式,因此它在我的第一列的旁边就会结束。

enter image description here enter image description here

创建行:

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);
    }
}

1 个答案:

答案 0 :(得分:3)

您可以尝试以相对布局包装imageview和textview。请注意我还没有测试下面的代码,但它改编自我的其他一些代码可以正常工作。

    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);
相关问题