Java tutorial
//package com.java2s; import android.util.DisplayMetrics; import android.util.Log; public class Main { private static DisplayMetrics mMetrics; /** * This method converts device specific pixels to density independent * pixels. NEEDS UTILS TO BE INITIALIZED BEFORE USAGE. * * @param px A value in px (pixels) unit. Which we need to convert into db * @return A float value to represent dp equivalent to px value */ public static float convertPixelsToDp(float px) { if (mMetrics == null) { Log.e("MPChartLib-Utils", "Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before" + " calling Utils.convertPixelsToDp(...). Otherwise conversion does not" + " take place."); return px; // throw new IllegalStateException( // "Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before // calling Utils.convertPixelsToDp(...)."); } DisplayMetrics metrics = mMetrics; float dp = px / (metrics.densityDpi / 160f); return dp; } }