如何专门检查android中是否存在一个drawable存在的名称会像以下那样工作:
#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