【问题标题】:Set alignment of ImageView programmatically以编程方式设置 ImageView 的对齐方式
【发布时间】:2014-08-12 07:56:26
【问题描述】:

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

我希望我的图片的对齐方式是左对齐,所以它在我的第一列旁边结束。

创建行:

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 只是一点点。 ImageView 中的图像显示在中心,但视图本身太大。如果我通过 ImageView 上的 LayoutParams 设置宽度,我的图像不再显示
  • 你能添加你用来设置宽度的代码吗?
  • 我做到了。我刚刚将 WRAP_CONTENT 添加到布局参数中,但是我再也看不到我的图像了。

标签: android alignment android-imageview android-tablelayout


【解决方案1】:

您可以尝试将 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);

【讨论】:

  • 当我使用它时,RelativeLayout 的图像和文本视图就消失了。它们必须对其他任何东西隐藏起来......
猜你喜欢
  • 2013-10-08
  • 2020-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
相关资源
最近更新 更多