Changing ConstraintLayout children's margin and size programmatically

7.3k views Asked by At

I'm writing a custom view to be able to use custom XML attributes to set a view's margin and size based on these attributes, everything worked fine until i got to the part where children of ConstraintLayout get's their margins and size determined by custom values. The margins doesn't make any difference and the view stays on the top left corner of its parent ConstraintLayout. What could be the problem? (The Image should be 500PXs away from the screen boundaries)

if (hasCustomWidth || hasCustomHeight || hasCustomTopMargin || hasCustomRightMargin || hasCustomBottomMargin || hasCustomLeftMargin) {
    if(((ViewGroup)getParent()) instanceof  LinearLayout) {
        LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight));
        ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) newLayoutParams;
        marginLayoutParams.setMargins((int) Math.round(customLeftMargin), (int) Math.round(customTopMargin), (int) Math.round(customRightMargin), (int) Math.round(customBottomMargin));
        setLayoutParams(newLayoutParams);
    } else if(((ViewGroup)getParent()) instanceof ConstraintLayout) {
        ConstraintLayout parentConstraintLayout = (ConstraintLayout)CustomAppCompatImageView.this.getParent();

        ConstraintLayout.LayoutParams newLayoutParams = new ConstraintLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight));

        ConstraintSet constraintSet = new ConstraintSet();

        constraintSet.clone(parentConstraintLayout);

        constraintSet.connect(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 500);
        constraintSet.setMargin(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, 500);

        setLayoutParams(newLayoutParams);
        constraintSet.applyTo(parentConstraintLayout);

        parentConstraintLayout.invalidate();
    } else {
        throw new RuntimeException("no listed parent LayoutParams subclass!");
    }

    invalidate();
}

Result:

enter image description here

1

There are 1 answers

1
chakmeshma On

I found the solution: apparently Android doesn't take ConstraintSet.LEFT and ConstraintSet.RIGHT as proper arguments, and must be replaced with ConstraintSet.START and ConstraintSet.END.