Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.

id title article sdk
Detect Screen Size

This recipe will show how to detect the screen size of a device, in density-independent pixels.


  1. Create a new Xamarin.Android application named ScreenSize .
  2. Edit Main.axml so that it contains two TextViews:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:text="Screen Width:"
        android:id="@+id/screenWidthDp" />
        android:text="Screen Height:"
        android:id="@+id/screenHeightDp" />
  1. Edit `Activity1.cs`, change the code in `OnCreate` to the following:
protected override void OnCreate(Bundle bundle)

    var metrics = Resources.DisplayMetrics;
    var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
    var heightInDp = ConvertPixelsToDp(metrics.HeightPixels);

    FindViewById<TextView>(Resource.Id.screenWidthDp).Text = "Screen Width: " + widthInDp + " dp.";
    FindViewById<TextView>(Resource.Id.screenHeightDp).Text = "Screen Height: " + heightInDp + " dp.";
  1. After `OnCreate`, add the following helper to convert the pixels into density-independent pixels:
private int ConvertPixelsToDp(float pixelValue)
    var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density);
    return dp;
  1. Run the application. Depending on the device, it will display the screen height and width. The following screen shot is from a Nexus 4:

Additional Information

The structure DisplayMetrics contains general information about a device’s display. DisplayMetrics.Width and DisplayMetrics.Height will return the width and height of a screen in pixels. The appearance of a user interface is influenced by not only by the resolution in pixels, but the physical screen size and the density of the pixels. To help deal with this complexity, Android has a virtual unit of measurement called density-independent pixels (dp). Using density-independent pixels allows an Android application to render elements of the UI so that they appear the same on all screens.

DisplayMetrics.Density is a scaling factor that can be used to convert from pixels to density-independent pixels.