如何在约束布局中动态设置ImageView的位置 [英] How can I set an ImageView's position dynamically in Constraint Layout
问题描述
我在一个约束布局中动态创建了ImageView.一旦运行该应用程序,由于未为ImageView定义任何位置,因此ImageView会显示在左上角. 如何动态设置ImageView的位置(假设为CENTER).
I have a dynamically created ImageView in one Constraint Layout. Once I run the app the ImageView is showing on left top corner because no position is defined for the ImageView. How can I set the position(let's say CENTER) of the ImageView dynamically.
我写了下面的代码
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);
layout.addView(imageView);
setContentView(layout);
任何建议都值得赞赏.
推荐答案
您将需要使用应用于ImageView
的ConstraintSet
将其居中. ConstraintSet
的文档可以在此处找到.
You will need to use a ConstraintSet
applied to the ImageView
to center it. The documentation for ConstraintSet
can be found here.
此类允许您以编程方式定义要与ConstraintLayout一起使用的一组约束.它使您可以创建和保存约束,并将其应用于现有的ConstraintLayout. ConstraintsSet可以通过多种方式创建...
This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways...
也许最棘手的事情是视图如何居中.在此处可以很好地说明居中技术.
Perhaps the trickiest thing here is how the view is centered. A good description of the centering technique is here.
对于您的示例,以下代码就足够了:
For your example, the following code will suffice:
// 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);
这篇关于如何在约束布局中动态设置ImageView的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!