jack_the_beast
jack_the_beast

Reputation: 1971

getDisplayMetrics().density vs dp

Do these two do the same in terms of mathematics? Do they produce the same result?

Java:

pixel=10;
margin=px * getResources().getDisplayMetrics().density;
layout_param.topMargin=margin;

XML:

android:layout_marginTop="10dp"

Upvotes: 3

Views: 6667

Answers (1)

slecorne
slecorne

Reputation: 1718

Yes, they are, the density inside getDisplayMetrics() is the one used for dip unit following the documentation:

public float density

Added in API level 1 The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

Upvotes: 2

Related Questions