The following code snippet shows how to converts dp unit to equivalent pixels, depending on device density. It returns a float value to represent px equivalent to dp depending on device density.

public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}
Tagged in : #Android

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.
  • Benjamin Noffsinger

    Where does the magic number 160 come from? [Edit] Nevermind, I should read more before I open my mouth. DP = 1.0 on a 160 dpi screen.