【问题标题】:Using layoutparams in relativeLayout with dp在 dp 中使用 relativeLayout 中的 layoutparams
【发布时间】:2023-04-09 02:47:01
【问题描述】:

我正在制作一个应用程序,我希望能够使用其边距动态移动视图。 我试过用这个:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)cover.getLayoutParams();
params.leftMargin= 470;
params.topMargin= 20;
cover.setLayoutParams(params); (cover is an ImageView)

此代码的问题在于它使用 px 而不是 dp。我还尝试使用 DisplayMetrics 将我的 px 值转换为 dp 但失败了。你能帮帮我吗?

【问题讨论】:

标签: java android android-relativelayout margin layoutparams


【解决方案1】:

需要根据dpi设置margin -

DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) MyActivity.this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

现在您可以将边距设置为 -

params.leftMargin = Math.round(470 * displayMetrics.density);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多