Get screen width and height in Android

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT - 
        game.findViewById(R.id.flag).getHeight());
}

Answers


Using this code you can get runtime Display's Width & Height

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

In a view you need to do something like this:

((Activity) getContext()).getWindowManager()
                         .getDefaultDisplay()
                         .getMetrics(displayMetrics);

In some scenario which devices have Navigatio Bar, have to check runtime

public boolean showNavigationBar(Resources resources)
    {
        int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        return id > 0 && resources.getBoolean(id);
    }

If Device have navigation bar then count its height

private int getNavigationBarHeight() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int usableHeight = metrics.heightPixels;
            getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            int realHeight = metrics.heightPixels;
            if (realHeight > usableHeight)
                return realHeight - usableHeight;
            else
                return 0;
        }
        return 0;
    }

So final height of device is

int height = displayMetrics.heightPixels + getNavigationBarHeight() ;

There is a very simple answer and without pass context

public static int getScreenWidth() {
    return Resources.getSystem().getDisplayMetrics().widthPixels;
}

public static int getScreenHeight() {
    return Resources.getSystem().getDisplayMetrics().heightPixels;
}

Note: if you want the height include navigation bar, use method below

WindowManager windowManager =
        (WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
    final Display display = windowManager.getDefaultDisplay();
    Point outPoint = new Point();
    if (Build.VERSION.SDK_INT >= 19) {
        // include navigation bar
        display.getRealSize(outPoint);
    } else {
        // exclude navigation bar
        display.getSize(outPoint);
    }
    if (outPoint.y > outPoint.x) {
        mRealSizeHeight = outPoint.y;
        mRealSizeWidth = outPoint.x;
    } else {
        mRealSizeHeight = outPoint.x;
        mRealSizeWidth = outPoint.y;
    }

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:

int Measuredwidth = 0;  
int Measuredheight = 0;  
Point size = new Point();
WindowManager w = getWindowManager();

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
    w.getDefaultDisplay().getSize(size);
    Measuredwidth = size.x;
    Measuredheight = size.y; 
}else{
    Display d = w.getDefaultDisplay(); 
    Measuredwidth = d.getWidth(); 
    Measuredheight = d.getHeight(); 
}

Why not

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

then use

displayMetrics.widthPixels (heightPixels)


Try below code :-

1.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

2.

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

or

int width = getWindowManager().getDefaultDisplay().getWidth(); 
int height = getWindowManager().getDefaultDisplay().getHeight();

3.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

metrics.heightPixels;
metrics.widthPixels;

DisplayMetrics dimension = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dimension);
        int width = dimension.widthPixels;
        int height = dimension.heightPixels;

public class DisplayInfo {
    int screen_height=0, screen_width=0;
    WindowManager wm;
    DisplayMetrics displaymetrics;

    DisplayInfo(Context context) {
        getdisplayheightWidth(context);
    }

    void getdisplayheightWidth(Context context) {
        wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        displaymetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displaymetrics);
        screen_height = displaymetrics.heightPixels;
        screen_width = displaymetrics.widthPixels;
    }

    public int getScreen_height() {
        return screen_height;
    }

    public int getScreen_width() {
        return screen_width;
    }
}

Get the value of screen width and height.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;

Methods shown here are deprecated/outdated but this is still working.Require API 13

check it out

Display disp= getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
disp.getSize(size);
int width = size.x;
int height = size.y;

DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;

Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();

It’s very easy to get in Android:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;

Full way to do it, that returns the true resolution:

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point size = new Point();
            wm.getDefaultDisplay().getRealSize(size);
            final int width = size.x, height = size.y;

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val config = context.resources.configuration
    val rotation = windowManager.defaultDisplay.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Configuration.ORIENTATION_LANDSCAPE
    else
        Configuration.ORIENTATION_PORTRAIT
}

/**
 * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
    val screenNaturalOrientation = getScreenNaturalOrientation(context)
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val point = Point()
    wm.defaultDisplay.getRealSize(point)
    val currentOrientation = context.resources.configuration.orientation
    if (currentOrientation == screenNaturalOrientation)
        return point
    else return Point(point.y, point.x)
}

For kotlin user's

fun Activity.displayMetrics(): DisplayMetrics {
   val displayMetrics = DisplayMetrics();
   windowManager.defaultDisplay.getMetrics(displayMetrics);
   return displayMetrics
}

And in Activity you could use it like

    displayMetrics().let { displayMetrics -> 
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
    }

Or in fragment

    activity?.displayMetrics()?.run {
        val height = heightPixels
        val width = widthPixels
    }

Just use the function below that returns width and height of the screen size as an array of integers

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;

    }

On your onCreate function or button click add the following code to output the screen sizes as shown below

 int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

I found weigan's answer best one in this page, here is how you can use that in Xamarin.Android:

public int GetScreenWidth()
{
    return Resources.System.DisplayMetrics.WidthPixels;
}

public int GetScreenHeight()
{
    return Resources.System.DisplayMetrics.HeightPixels;
}

Screen resolution is total no of pixel in screen. Following program will extract the screen resolution of the device. It will print screen width and height. Those values are in pixel.

public static Point getScreenResolution(Context context) {
// get window managers
WindowManager manager =  (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);

 // get width and height
 int width = point.x;
 int height = point.y;

 return point;

}


This set of utilities to work with the Size abstraction in Android.

It contains a class SizeFromDisplay.java You can use it like this:

ISize size = new SizeFromDisplay(getWindowManager().getDefaultDisplay());
size.width();
size.hight();

Two steps. First, extend Activity class

class Example extends Activity

Second: Use this code

 DisplayMetrics displayMetrics = new DisplayMetrics();
 WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
 windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
 int deviceWidth = displayMetrics.widthPixels;
 int deviceHeight = displayMetrics.heightPixels;

Try this code for Kotlin

 val display = windowManager.defaultDisplay
 val size = Point()
 display.getSize(size)
 var DEVICE_WIDTH = size.x
 var DEVICE_HEIGHT = size.y

None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.

When looking for the current configuration, always use the configuration from your current activity in getResources().getConfiguration(). Do not use the configuration from your background activity or the one from the system resource. The background activity does not have a size, and the system's configuration may contain multiple windows with conflicting sizes and orientations, so no usable data can be extracted.

So the answer is

val config = context.getResources().getConfiguration()
val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp

       @Override
        protected void onPostExecute(Drawable result) {
            Log.d("width",""+result.getIntrinsicWidth());
            urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 600);

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();

            // For ICS
            URLImageParser.this.container.setHeight((400+URLImageParser.this.container.getHeight()
                    + result.getIntrinsicHeight()));

            // Pre ICS`enter code here`
            URLImageParser.this.container.setEllipsize(null);
        }

Need Your Help

How to get StackPanel's children to fill maximum space downward?

wpf xaml autolayout autoresize dockpanel

I simply want flowing text on the left, and a help box on the right.

MATLAB heat map

matlab heatmap

I am trying to create a heat map using MATLAB, but the default function in MATLAB program doesn't any sense to me.