在使用的RelativeLayout用的LayoutParams DP [英] Using layoutparams in relativeLayout with dp

查看:707
本文介绍了在使用的RelativeLayout用的LayoutParams DP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

这篇关于在使用的RelativeLayout用的LayoutParams DP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆