get Screen Width Dp - Android Phone

Android examples for Phone:Screen

Description

get Screen Width Dp

Demo Code


//package com.java2s;

import android.content.Context;

import android.graphics.Rect;

import android.util.DisplayMetrics;

import android.view.WindowManager;

public class Main {
    public static int getScreenWidthDp(Context context) {
        return (int) px2dip(context, getScreenWidthPx(context));
    }/*from   ww  w .j  av  a2 s. co  m*/

    public static float px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxValue / scale);
    }

    public static Rect px2dip(Context context, Rect rect) {
        int left = (int) px2dip(context, rect.left);
        int top = (int) px2dip(context, rect.top);
        int right = (int) px2dip(context, rect.right);
        int bottom = (int) px2dip(context, rect.bottom);
        return new Rect(left, top, right, bottom);
    }

    public static int getScreenWidthPx(Context context) {
        return getDisplayMetrics(context).widthPixels;
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        return dm;
    }
}

Related Tutorials