首页 > 解决方案 > ConstraintSet.connect() 中的边距参数是 px 还是 dp?

问题描述

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

应用为margin像素还是依赖于密度的像素?

散布在网络上的各种文章和杜撰的知识似乎并不一致。我正在寻找官方文件或来源证据。

标签: android

解决方案


margin参数应以像素为单位提供

我最终追踪ConstraintSet.applyTo(ConstraintLayout)ConstraintSet.applyToInternal(ConstraintLayout),发现在这里, a 的每个孩子ConstraintLayout都有其LayoutParams复制并传递给ConstraintSet.Constraint.applyTo(LayoutParams)。然后将所有参数(未经修改)从 复制ConstraintSet.Constraint到 中LayoutParams,然后将修改LayoutParams后的分配回子项。我认为这是提供的保证金参数应遵循LayoutParams规则的具体证据。

在 ConstraintSet.java 中

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

applyToInternal(ConstraintLayout)申报时

    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);
        //...
    }

    //...

applyTo(LayoutParams)申报时

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

推荐阅读