Xamarin - Does Android Drawable Exist?



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

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

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

在Android中,我认为它应该是AssemblyResources的一部分,但这只是返回了我的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中按名称具体检查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

相关内容

最新更新