-4

I want to set layout_marginTop to 800px using setLayoutParams(). But I want know what would be this value in dp unit?

Thanks in advance.

Zerntrino
  • 67
  • 1
  • 8
  • `LayoutParams` expects pixel. You have to be more specific... – Knickedi May 12 '12 at 18:25
  • 1
    If you're trying to convert dip to px then here it is: `int px = (int) (dip * mContext.getResources().getDisplayMetrics().density + 0.5f)`. I still do not understand what you're trying to achieve. – Knickedi May 12 '12 at 18:41
  • main idea in questions is convert pixels to dp. I want to know 1dp = ?px in my screen. – Zerntrino May 12 '12 at 18:43
  • 1
    1 dip = `mContext.getResources().getDisplayMetrics().density`. So dip depends on the current device configuration. You should mention that in your question, so other people know what you're searching for. – Knickedi May 12 '12 at 18:50
  • Sorry I change question for people understanding in my question. – Zerntrino May 12 '12 at 19:02
  • You were already given the answer, in the upvoted comments. The rest is basic arithmetic. – CommonsWare May 12 '12 at 19:15
  • my screen 552x1024 I want to set margin top 800px. How many set dip in LayoutParams margin top – Zerntrino May 12 '12 at 19:24
  • Sorry I change question for people understanding in my question again. – Zerntrino May 12 '12 at 19:33

1 Answers1

2

The logical density of the display is given in the DisplayMetrics class, and can be retrieved with,

getResources().getDisplayMetrics().density

Thus, to convert dp to px, you would do,

int density = getResources().getDisplayMetrics().density;
int px = (int) (dp * density);

To convert px to dp, just perform the inverse operation,

int dp = px/density;
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250