我正在 MVVMCross 的 Android 应用程序中创建收藏夹汽车列表。我的问题是在该列表中动态加载图像。我的观点是,每辆车的 ImageView 正在获取转换器拍摄并返回 BitmapDrawable 对象的图片 ID。它适用于我的 Windows Phone 应用程序,但在 Android 中我遇到了一个小问题。代码如下所示:
<LinearLayout
android:id="@+id/PeoplePanel"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/transparent"
android:layout_below="@id/TitleTextView"
android:paddingTop="3dip"
android:paddingLeft="10dip">
<ImageView
android:id="@+id/imagePhoto"
android:layout_width="70dp"
android:layout_height="70dp"
local:MvxBind="{'ResourcesImagePath':{'Path':'Item.Obj.IDZdjeciaGlownego', 'Converter':'ByteToImg'}}"/>
转换器是:
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var id = (int?)value;
if (id != null)
{
var Service = this.GetService<IKomisSamService>();
var img = Service.GetImage((int)id);
try
{
var drawable = BitmapFactory.DecodeByteArray(img, 0, img.Length);
return new BitmapDrawable(drawable);
}
catch { }
}
return null;
..和输出:
04-12 11:13:06.034 I/MvxBind ( 856): 135.42 Failed to create target binding for from Item.Obj.IDZdjeciaGlownego to ResourcesImagePath
MvxBind:Warning:135.42 Failed to create target binding for from Item.Obj.IDZdjeciaGlownego to ResourcesImagePath
04-12 11:13:06.034 I/mono-stdout( 856): MvxBind:Warning:135.42 Failed to create target binding for from Item.Obj.IDZdjeciaGlownego to ResourcesImagePath
04-12 11:13:06.644 D/dalvikvm( 856): GC_EXTERNAL_ALLOC freed 1850 objects / 93880 bytes in 48ms
转换器运行两次:第一次是请求服务获取项目,第二次是在下载时运行以获取它并返回 BitmapDrawable 对象。
我认为我的问题出在 MvxBind 中,我不应该使用 ResourcesImagePath 而是其他获取 BitmapDrawable 对象而不是他的路径的东西。 提前致谢!
最佳答案
一般来说:
- MvvmCross 中有“内置”绑定(bind),用于显示来自 Assets 和
ImageView
中的资源的图像 MvxImageView
使显示下载的图像变得非常简单 - 只需使用ImageUrl
并确保加载了 DownloadCache 和 File 插件。- 在 v3 中,还有一个现成的绑定(bind)可用于在
ImageView
中显示Byte[]
(在 PictureChooser 插件中)
但是,对于您想要添加自己的绑定(bind)的一般情况,您可以自己执行此操作...
但是您不能仅通过发明 ResourcesImagePath
并使用值转换器来做到这一点。 ImageView
没有 ResourcesImagePath
属性 - 因此 Mvx 系统在这种情况下没有任何绑定(bind)。
相反:
您需要使用如下类定义绑定(bind)操作:https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Binding.Droid/Target/MvxImageViewDrawableTargetBinding.cs
然后您需要(在您的
设置
期间)告诉 mvvmcross 如何使用该绑定(bind) - 例如就像第 63 行:https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Binding.Droid/MvxAndroidBindingBuilder.cs#L63
这样做称为“创建自定义绑定(bind)”
注意:我不完全确定“转换器正在运行两次”- 不确定您的意思(听起来像是一个单独的问题)
重要说明 - 为避免位图内存泄漏,请对动态加载的所有位图使用 InPurgeable
关于android - 在 ImageView 中返回 BitmapDrawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15969930/