如何在 Constraint Layout 中动态设置 ImageView 的位置

4

我在一个 ConstraintLayout 中动态创建了一个 ImageView。一旦我运行应用程序,由于没有为 ImageView 定义位置,因此它将显示在左上角。

如何在动态设置 ImageView 位置(比如设置到中心)?

我已经编写了以下代码:

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);

ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);

layout.addView(imageView);

setContentView(layout);

非常感谢您的建议。

1个回答

5
您需要使用应用于ImageViewConstraintSet来使其居中。 ConstraintSet的文档可以在这里找到。

该类允许您以编程方式定义一组用于ConstraintLayout的约束条件。它让您创建和保存约束条件,并将其应用于现有的ConstraintLayout。 ConstraintsSet可以通过各种方式创建...

也许这里最棘手的问题是视图的居中。 这里提供了一个很好的居中技术的描述,点击此处
对于您的示例,以下代码足以满足要求:
    // Get existing constraints into a ConstraintSet
    ConstraintSet constraints = new ConstraintSet();
    constraints.clone(layout);
    // Define our ImageView and add it to layout
    ImageView imageView = new ImageView(this);
    imageView.setId(View.generateViewId());
    imageView.setImageResource(R.drawable.redlight);
    layout.addView(imageView);
    // Now constrain the ImageView so it is centered on the screen.
    // There is also a "center" method that can be used here.
    constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
            0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP,
            0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
    constraints.applyTo(layout);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接