gpt4 book ai didi

android - 如何在约束布局中动态生成的 View 上添加 dp 边距

转载 作者:行者123 更新时间:2023-11-30 00:02:41 26 4
gpt4 key购买 nike

我在约束布局中添加了 2 个来自 xml 的 View ,现在我需要在从 xml 创建的 View 下方添加新 View

这就是我添加新 View 所做的

//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,但它只是在 View 上添加了一条细线,如果我使用 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());

关于android - 如何在约束布局中动态生成的 View 上添加 dp 边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49629435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com