Skip to content

Instantly share code, notes, and snippets.

@geirsagberg
Created January 21, 2015 13:28
Show Gist options
  • Save geirsagberg/f25ebf75b4762745054a to your computer and use it in GitHub Desktop.
Save geirsagberg/f25ebf75b4762745054a to your computer and use it in GitHub Desktop.
Polymorphic list adapter for MvvmCross Android
public class PolymorphicListAdapter : MvxAdapter
{
private IDictionary<Type, int> TemplateIdByType { get; set; }
public override int ViewTypeCount
{
get { return TemplateIdByType.Count; }
}
private PolymorphicListAdapter(Context context, IMvxAndroidBindingContext bindingContext) : base(context, bindingContext)
{
}
public static PolymorphicListAdapter Create(Context context, IMvxAndroidBindingContext bindingContext, IDictionary<Type, int> templateIdByType)
{
if (templateIdByType == null)
throw new ArgumentNullException("templateIdByType");
if (templateIdByType.IsEmpty())
throw new ArgumentException("Need at least one templateID and type");
var adapter = new PolymorphicListAdapter(context, bindingContext);
adapter.TemplateIdByType = templateIdByType;
return adapter;
}
public override int GetItemViewType(int position)
{
var item = GetRawItem(position);
return TemplateIdByType.Keys.ToList().IndexOf(item.GetType());
}
protected override View GetBindableView(View convertView, object dataContext, int templateId)
{
templateId = TemplateIdByType[dataContext.GetType()];
return base.GetBindableView(convertView, dataContext, templateId);
}
}
@geirsagberg
Copy link
Author

Usage in Fragment:

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var view = base.OnCreateView(inflater, container, savedInstanceState);

        var list = view.FindViewById<MvxListView>(Resource.Id.AnimalList);
        list.Adapter = PolymorphicListAdapter.Create(Activity, (IMvxAndroidBindingContext) BindingContext, new Dictionary<Type, int>{
            {typeof(KittenViewModel), Resource.Layout.ListItem_Kitten},
            {typeof(PuppyViewModel), Resource.Layout.ListItem_Puppy}
        });

        return view;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment