在relativeLayout中使用dp的layoutparams

mre*_*re1 2 java android margin relativelayout layoutparams

我正在创建一个应用程序,我希望能够动态地使用其边距移动视图.我试过用这个:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)cover.getLayoutParams();
params.leftMargin= 470;
params.topMargin= 20;
cover.setLayoutParams(params); (cover is an ImageView)
Run Code Online (Sandbox Code Playgroud)

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

Vis*_*ale 11

您需要根据dpi设置保证金 -

DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) MyActivity.this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
Run Code Online (Sandbox Code Playgroud)

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

params.leftMargin = Math.round(470 * displayMetrics.density);
Run Code Online (Sandbox Code Playgroud)