Device specific code in Xamarin

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

Occasionally we might need to handle text or UI controls slightly differently on different devices.

In a shared code project we’d probably look to write code using conditional compilation, but this wouldn’t work for PCL code. Also conditional compilation doesn’t work in XAML. So whilst conditional compilation is still a valid technique for shared code projects an alternative is runtime branching based upon the device the code is running on (in other words if or switch code). Xamarin already supplies us with a simple mechanism to achieve this using the OnPlatform method on the Device class.

PCL/Runtime device specific code

So, in code we can use the Device class like this

public class MyPage : ContentPage
{
   public MyPage()
   {
      Padding = Device.OnPlatform(
          new Thickness(0,20,0,0), 
          new Thickness(0),
          new Thickness(0));
   }
}

Or from XAML we can use the OnPlatform element, for example

<ContentPage>
   <ContentPage.Padding>
      <OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" />
   </ContentPage.Padding>
</ContentPage>

Conditional Compilation directives

Just to complete the picture, let’s look at what compiler directives exist – these are not exclusive to shared code projects but obviously are available for any use

  • __IOS__ for iOS code
  • __ANDROID__ for Android code
  • __ANDROID_nn__ for Android code, where nn is the Andoird API level supported
  • WINDOWS_UWP for Universal Windows Platform code
  • WINDOWS_APP for Windows 8.1 code
  • WINDOWS_PHONE_APP for Windows Phone 8.1 code