문제

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 ?

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top