Converting pixels to dp unit on Android

posted in: Android, tricks | 0


As you may now, on the Android platform we have to deal with a huge amount of devices with different specs. And one thing that can change a lot is the screen size. If you’re building an app you need to consider it may be run by users having different devices from smartphone to smartwatches and TV. Maybe more and more desktop also?


So you always have to build layouts that will fit any screen. In Android, when it comes to describing user interfaces we most of the time speak in dp. So what is dp? When I started Android development I was more familiar with the pixel unit. DP is a safe unit that take care of the screen density. The screen density may be seen as the number of pixels per centimeters (or inches).

On Android, at run time, the platform transparently handles any scaling of the dp units needed, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple:

pixels = dps * (density / 160)

For example, on 240 dpi screen, 1 dp would equal 1.5 physical pixels. This means we can develop great UIs that will have the same physical size on any screen.


Why do I need it?


Most of the use case of converting dp to pixels come when you are inflating a view from code. For example, let’s say I’m inflating a linear layout and I want to set the size (width and height), the asked parameters will be pixels and not dp. So that’s where I need to make the conversion. For example:

But we don’t want to set manual pixels here, we prefer describing our UI in dp.


The Snippet


Here is a snippet I constantly grab from StackOverflow for doing conversions between pixels and dp:



The snippet also provide the opposite conversion which couls come in hand if you are doing the opposite job of the example. If you getHeight()  or getWidth()  of a view. The value will be in pixels too..



Thanks for reading, this is just a reminder for myself and in case people wants to get this snippet too.