Android How to convert Dp to Px and Px to Dp


If you are developing an android application that is based on inflating views at runtime and are dependent on height and width of the screen. You often need to convert between real pixel (px) and device independent pixel (dp, dip).
Most of the use case of converting dp to pixels come when you are inflating a view from code. For example, we are inflating a linear layout and have to set the size (width and height), the asked parameters will be pixels and not dp. So that’s where we need to make the conversion.

The following code snippet will help you convert from dp to px and px to dp.

Dp to Px

Px to Dp

Enjoy Coding and Share Knowledge




Show Buttons
Hide Buttons