Android Studio 约束布局更改绝对

Android Studio constraint layout change absolute

我需要编辑 ImageView 的绝对值:

tools:layout_editor_absoluteY="0dp"

tools:layout_editor_absoluteY="50dp"

但在 java 如果我只是这样做

ImageView img = (ImageView)findViewById(R.id.mainView);
ConstraintLayout.LayoutParams params1 = (ConstraintLayout.LayoutParams)(img.getLayoutParams());
params1.editorAbsoluteY = 50;
img.setLayoutParams(params1);

没用。

LayoutParams 总是处理像素值。

因此,在 LayoutParams 上设置值之前,您需要将 DP 值转换为 PX 值。有很多这样的例子,快速 google 应该做到。

如果这不起作用,您需要提供更多信息,而不仅仅是说 "it doesn't work"。

将您的值从 DP 转换为像素:

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}

在设置 params1.editorAbsoluteY 之前。