سؤال

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