Ashim007
Ashim007

Reputation: 17

How can I find out the device's height and width using xamarin

I am using Xamarin and I don't know how to find out the device's height and width . I have searched online as well but it does not have anything with xamarin. All of them are related to something else. I want to build an application that has responsive layout, by using the height and width I can find out the position of the device and implement code with the condition of the device.

Can anyone suggest me ".cs" codes for finding the height and width of the screen?

Upvotes: 0

Views: 2214

Answers (3)

Nicolas Bodin
Nicolas Bodin

Reputation: 1591

Common code (in App.xaml.cs)

public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}

Android part (in MainActivity.cs, in the OnCreate method)

App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);

iOS part (in AppDelegate.cs, in the FinishedLaunching method)

App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;

So App.ScreenHeight and App.ScreenWidth will be initialized when the App will be launched, then you will be able to use them anywhere in the common code.

Upvotes: 2

CDrosos
CDrosos

Reputation: 2528

The correct way to hande layouts for every resolution is with different layout files declared for a range of screens, like it is described here: https://developer.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_4_-_creating_resources_for_varying_screens/

Don't make one layout that handle all the cases, your code will be a mess and you will have to implement funcions that already exist and works in the above document,

Because i see that you don't have a reputation i will advice you this:

Always first search for the correct way to build something, then search on how to build with the way you select

Upvotes: 0

Jason
Jason

Reputation: 89214

For Android:

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

For iOS:

UIScreen.MainScreen.Bounds

Upvotes: 2

Related Questions