在使用的RelativeLayout用的LayoutParams DPRelativeLayout、LayoutParams、DP

2023-09-06 09:56:04 作者:不走寻常路的骚年

我米做一个应用程序,我想能够移动使用它的利润率动态视图。我尝试使用这样的:

I m making an app and i want to be able to move a view using its margins dynamically. I tried using this :

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

本code公司,它使用像素而不是DP的问题。我用DisplayMetrics转换我的像素值DP还尝试过但失败了。你能帮助我吗?

The problem with this code its that it uses px instead of dp. I also tried using DisplayMetrics to convert my px values to dp but failed . Can you help me ?

推荐答案

您需要根据DPI设定保证金 -

You need to set margin according to dpi -

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

现在你可以设置保证金为 -

Now you can set margin as -

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