April 20, 2017

Android How to convert Dp to Px and Px to Dp

By Lalit Vasan


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 Dp to Px android and 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.

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(50, 50); // 50 are Pixels!!!
yourButton.setLayoutParams(layoutParams);

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

Dp to Px

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp      A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public float convertDpToPx(Context context, float dp) {
        return dp * context.getResources().getDisplayMetrics().density;
    }

Px to Dp

    
    /**
     * This method converts device specific pixels to density independent pixels.
     *
     * @param px      A value in px (pixels) unit. Which we need to convert into db
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent dp equivalent to px value
     */
    public float convertPxToDp(Context context, float px) {
        return px / context.getResources().getDisplayMetrics().density;
    }

Enjoy Coding and Share Knowledge