0

我在一个约束布局中有一个动态创建的ImageView。一旦我运行应用程序,ImageView将显示在左上角,因为没有为ImageView定义位置。 如何动态设置ImageView的位置(比方说CENTER)。如何在约束布局中动态设置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

您将需要使用应用于ImageViewConstraintSet来居中。 ConstraintSet的文档可以在here找到。

该类允许您以编程方式定义与ConstraintLayout一起使用的一组约束。它允许您创建和保存约束,并将它们应用于现有的ConstraintLayout。 ConstraintsSet可以以各种方式创建...

也许这里最棘手的事情是视图如何居中。对中技术的一个很好的描述是here

对于你的榜样,下面的代码就足够了:

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