Monday, October 16, 2017

Platform specificity

In the section of that XAML file involving the ToolbarItem, you can also see a tag named OnPlatform. This is one of several techniques in Xamarin.Forms that allow introducing some platform speci-ficity in otherwise platform-independent code or markup. It’s used here because each of the separate platforms has somewhat different image format and size requirements associated with these icons.

A similar facility exists in code with the Device class. It’s possible to determine what platform the code is running on and to choose values or objects based on the platform. For example, you can specify different font sizes for each platform or run different blocks of code based on the platform. You might want to let the user manipulate a Slider to select a value in one platform but pick a number from a set of explicit values in another platform.

In some applications, deeper platform specificities might be desired. For example, suppose your application requires the GPS coordinates of the user’s phone. This is not something that Xamarin.Forms provides, so you’d need to write your own code specific to each platform to obtain this information.

The DependencyService class provides a way to do this in a structured manner. You define an interface with the methods you need (for example, IGetCurrentLocation) and then implement that interface with a class in each of the platform projects. You can then call the methods in that interface from the Xamarin.Forms project almost as easily as if it were part of the API.

Each of the standard Xamarin.Forms visual objects—such as Label, Button, Switch, and Slider—are supported by a renderer class in the various Xamarin.Forms.Platform libraries. Each renderer class implements the platform-specific object that maps to the Xamarin.Forms object.

You can create your own custom visual objects with your own custom renderers. The custom visual object goes in the common code project, and the custom renderers go in the individual platform projects. To make it a bit easier, generally you’ll want to derive from an existing class. Within the individual Xamarin.Forms platform libraries, all the corresponding renderers are public classes, and you can derive from them as well.

Xamarin.Forms allows you to be as platform independent or as platform specific as you need to be. Xamarin.Forms doesn’t replace Xamarin.iOS and Xamarin.Android; rather, it integrates with them.

Source of Information : Creating Mobile Apps with Xamarin.Forms

No comments: