Xamarin - Android Drawable 是否存在?

Xamarin - Does Android Drawable Exist?

在 Xamarin Forms (3.0) 应用程序中,我将使用什么方法从共享项目代码中判断我的 Android 项目中是否存在可绘制资源?

在 iOS 中,我可以使用 NSFileManager 查看文件是否存在于我的 iOS 项目的 "Resources" 文件夹中:

#if __IOS__
private bool DoesImageExist(string image)
{
    //WORKS
    return Foundation.NSFileManager.DefaultManager.FileExists(image);
}
#endif

在 Android 中,我认为它应该是程序集资源的一部分,但那只是 returns 我的 App.xaml 文件。

#if __ANDROID__
private bool DoesImageExist(string image)
{
    //DOES NOT WORK
    if(MyApp.Current?.GetType() is Type type)
        foreach (var res in Assembly.GetAssembly(type).GetManifestResourceNames())
        {
            if (res.Equals(image, StringComparison.CurrentCultureIgnoreCase))
                return true;
        }
    return false;
}
#endif

如何具体检查 android 中的可绘制对象是否按名称存在将像这样工作:

#if __ANDROID__
public bool DoesImageExist(string image)
{
    var context = Android.App.Application.Context;
    var resources = context.Resources;
    var name = Path.GetFileNameWithoutExtension(image);
    int resourceId = resources.GetIdentifier(name, "drawable", context.PackageName);

    return resourceId != 0;
}
#endif

如果您的代码在 pcl 或 .net 标准程序集中,您将必须创建一个抽象。某种 Ioc 库对此很有效。您还可以让 Android 或 iOS 实现抽象接口并使其在某处作为单例可用。它不是那么优雅,但它会起作用。

基本上你会实现这样的东西:

public interface IDrawableManager
{
    bool DoesImageExist(string path);
}

然后有两种实现方式:

public class DroidDrawableManager : IDrawableManager
{
        var context = Android.App.Application.Context;
        var resources = context.Resources;
        var name = Path.GetFileNameWithoutExtension(image);
        int resourceId = resources.GetIdentifier(name, "drawable", context.PackageName);

        return resourceId != 0;
}

public class IOSDrawableManager : IDrawableManager
{
    public bool DoesImageExist(string image)
    {
        return Foundation.NSFileManager.DefaultManager.FileExists(image);
    }
}

我已将工作示例上传到 github:

https://github.com/curtisshipley/ResourceExists