问题
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.
I have written below code
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);
layout.addView(imageView);
setContentView(layout);
Any suggestion is highly appreciated.
回答1:
You will need to use a ConstraintSet
applied to the ImageView
to center it. The documentation for ConstraintSet
can be found here.
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);
来源:https://stackoverflow.com/questions/44358440/how-can-i-set-an-imageviews-position-dynamically-in-constraint-layout