How can I set an ImageView's position dynamically in Constraint Layout

时光毁灭记忆、已成空白 提交于 2019-12-06 11:02:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!