Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms Different View Per Platform

So I'm new to Xamarin development and I have a question that I haven't been able to find an answer for. Is it possible to implement a view so that it looks different on each platform or maybe even one? IE - The view looks similar on iOS and Android, but for a UWP desktop app it maybe has more available controls because there is more screen space. Thanks in advance.

like image 510
tldragoon Avatar asked Apr 11 '18 15:04

tldragoon


People also ask

What are views in Xamarin forms?

The visual elements in Xamarin. Forms fall into two separate categories: controls and arrangers. Both are considered visual elements, share a common base class (View), and are collectively known as Views.


1 Answers

Of course you can. The simplest way is to use the OnPlatform (see here) tag in your XAML

<OnPlatform x:TypeArguments="View">
    <On Platform="iOS">
        <!-- Use view for iOS here -->
    </On>
    <On Platform="Android">
        <!-- Use view for Android here -->
    </On>
    <On Platform="UWP">
        <!-- Use view for UWP here -->
    </On>
</OnPlatform>

In your case (using the same view for Android and iOS) you could simplify this to

<OnPlatform x:TypeArguments="View">
    <On Platform="iOS, Android">
        <!-- Use view for iOS here -->
    </On>
    <On Platform="UWP">
        <!-- Use view for UWP here -->
    </On>
</OnPlatform>

If you are creating the views in code, you could use Device.RuntimePlatform

View CreateViewForCurrentPlatform()
{
    switch(Device.RuntimePlatform)
    {
        case Device.iOS:
        case Device.Android:
            return new View1();
        case Device.UWP:
            return new View2();
    }
    throw new Exception("Unsupported platform");
}

Anyway, since you said that

[...] for a UWP desktop app it maybe has more available controls because there is more screen space.

you should think about using Device.Idiom instead (see here), which allows you to discriminate between tablets, desktops and phones. Android and iOS are running on tablets too and it would be a pity to waste screen space on those.

like image 148
Paul Kertscher Avatar answered Nov 02 '22 21:11

Paul Kertscher