androidmarginpixeldensity-independent-pixelconstraintset

Is ConstraintSet.connect() margin parameter in px or dp?


val margin = 8
ConstraintSet().apply {
  connect(anId, ConstraintSet.START, anotherId, ConstraintSet.START, margin)
}

Is margin applied as pixels or density-dependent pixels?

Various articles scattered around the web and apocryphal knowledge seem not to agree on one or the other. I'm looking for official documentation or source evidence.


Solution

  • The margin parameter should be supplied in pixels.

    I ended up tracing the ConstraintSet.applyTo(ConstraintLayout) down to ConstraintSet.applyToInternal(ConstraintLayout) and found that here, each child of a ConstraintLayout has its LayoutParams copied and passed to ConstraintSet.Constraint.applyTo(LayoutParams). Which then copies all the parameters (without modification) from the ConstraintSet.Constraint into the LayoutParams and then assigns the modified LayoutParams back to the child. I think this is concrete evidence that the supplied margin parameters should follow the LayoutParams rules.

    in ConstraintSet.java

        this.applyToInternal(constraintLayout);
        constraintLayout.setConstraintSet((ConstraintSet)null); }
    

    at applyToInternal(ConstraintLayout) declaration

        int count = constraintLayout.getChildCount();
    
        //...
    
        LayoutParams param;
        for(int i = 0; i < count; ++i) {
            View view = constraintLayout.getChildAt(i);
            //...
            param = (LayoutParams)view.getLayoutParams();
            constraint.applyTo(param);
            view.setLayoutParams(param);
            //...
        }
    
        //...
    

    at applyTo(LayoutParams) declaration

        //...
        param.leftMargin = this.leftMargin;
        param.rightMargin = this.rightMargin;
        param.topMargin = this.topMargin;
        param.bottomMargin = this.bottomMargin;
        //...