Xamarin – How to create cross platform class?

Define cross interfaces in common project

// 1. Define cross interfaces
public interface ISomething1
{
    ...
}

public interface ISomething2
{
    ...
}

Define cross classes in common project

// 2. Define cross classes
namespace XXX.YYY
{
    public static class CrossSomething
    {
        public static ISomething1 Something1 { get; } = Xamarin.Forms.DependencyService.Get<ISomething1>();
        public static ISomething2 Something2 { get; } = Xamarin.Forms.DependencyService.Get<ISomething2>();
    }
}

Code functions in specific platform

// 3. Code functions in specific platform
// 3.1 Android
[assembly: Xamarin.Forms.Dependency(typeof(XXX.YYY.Droid.SpecificPlatformDroid))]
namespace XXX.YYY.Droid
{
    public class SpecificPlatformDroid1 : ISomething1
    {
        public Method1() {
            ...
        }

        ...
    }

    public class SpecificPlatformDroid2 : ISomething2
    {
        ...
    }
}

// 3.2 iOS
[assembly: Xamarin.Forms.Dependency(typeof(XXX.YYY.iOS.SpecificPlatformIOS))]
namespace XXX.YYY.iOS
{
    public class SpecificPlatformIOS1 : ISomething1
    {
        public Method1() {
            ...
        }

        ...
    }

    public class SpecificPlatformIOS2 : ISomething2
    {
        ...
    }
}

Usage in common project

// 4. Usage in common project
CrossSomething.Something1.Method1();

Be the first to comment

Leave a Reply

Your email address will not be published.


*