我构建了一个转换器,它将可绘制名称转换为位图并将位图绑定到 ImageView。
转换器:
public class ImageNameToBitmapConverter : MvxValueConverter<string, Bitmap>
{
protected override Bitmap Convert(string value, Type targetType, object parameter, CultureInfo culture)
{
var topActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
var bm = BitmapFactory.DecodeResource(topActivity.Activity.Resources, GetResourceId(value, "drawable", topActivity));
return bm;
}
private static int GetResourceId(string variableName, string resourceName, IMvxAndroidCurrentTopActivity topActivity)
{
try
{
return topActivity.Activity.Resources.GetIdentifier(variableName, resourceName, topActivity.Activity.PackageName);
}
catch (Exception)
{
return -1;
}
}
}
XML 视图:
<ImageView
local:MvxBind="Bitmap Icon, Converter=ImageNameToBitmap"
android:layout_width="100dp"
android:layout_height="100dp" />
Icon
我绑定的属性是一个字符串,如:“ icon_name ”,我将图像icon_name.png
放在 Android 项目的Resources/drawable