The following code snippet shows how to convert device specific pixels to density independent pixels. It returns a float value to represent dp equivalent to px value

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


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