开发者

Is it wise to use "dp" instead of something else?

开发者 https://www.devze.com 2023-03-26 03:58 出处:网络
In Android when Im measuring, is it wise to use DP, or something else? Im scared that dp might change from device to device and my app will look horrible in anything other 开发者_如何学Pythonthan my p

In Android when Im measuring, is it wise to use DP, or something else? Im scared that dp might change from device to device and my app will look horrible in anything other 开发者_如何学Pythonthan my phone.


You should ALWAYS use dp. If you need the value in pixels, you could use this method -

public static int dpToPixels(Context context, float dp) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dp * scale + 0.5f);
}


always use dip

density independant pixel


If you look at the reference documentation you'll see that's the point of dp. Specifically,

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

So unless you want to be limited to a single screen size and density, always use dp.


Qasim, dp or dip was invented to prevent what your afraid of. Check out this article: http://developer.android.com/guide/practices/screens_support.html, as well as this other question: What is the difference between "px", "dp", "dip" and "sp" on Android?


In addition to dp, you may also use pt (point = 1/72 of an inch), in (inch) and mm (millimeter).

Since all of these units are based on actual physical size, your UI elements will retain the same physical size on any device.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号