Using layoutparams in relativeLayout with dp

主宰稳场 提交于 2019-12-09 22:24:09

问题


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)

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 ?


回答1:


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


来源:https://stackoverflow.com/questions/18799968/using-layoutparams-in-relativelayout-with-dp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!