如何在约束布局中动态生成的视图上添加 dp 边距

How to add margin in dp on dynamically generated views in constraint layout

我在约束布局中添加了 xml 的 2 个视图,现在我需要在 xml

创建的视图下方添加新视图

这就是我添加新视图的方法

//leftMargin calculation
int topMargin= Utils.pxToDp(20);
ImageView imageView = new ImageView(this);
imageView.setId(View.generateViewId());
constraintLayout.addView(imageView);

ConstraintSet set = new ConstraintSet();
set.clone(constraintLayout);
set.constrainWidth(imageView.getId(), ConstraintSet.MATCH_CONSTRAINT);

set.connect(imageView.getId(), ConstraintSet.TOP, eventsViewPager.getId(), ConstraintSet.BOTTOM, topMargin);

我在这里定义边距20dp,但它只是在视图上添加了一条细线,如果我使用 400 左右的边距,那么它会给我想要的结果,一定是转换有误可能是我在这里做的。

这就是我将值从 px 转换为 dp

的方式
public static int pxToDp(int px){
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

我认为你应该将 DP 转换为像素而不是反之,使用 TypedValue 像这样:

int marginTopDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, 
                              getResources().getDisplayMetrics());