Search code examples
mvvmcross

How to group by in MvvmCross RecyclerView?


How to group by in MvvmCross RecyclerView? MvvmCross.Droid.Support.V7.RecyclerView 6.1.2

 <MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView               
                android:id="@+id/recyclerView"
                android:scrollbars="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:MvxItemTemplate="@layout/appointment_feed_item" 
                app:MvxBind="ItemsSource Items" />

Solution

  • MvvmCorss includes a neat mechanism for this since version 4.1.5. It’s called TemplateSelector and defined in the interface IMvxTemplateSelector. The purpose of this interface is to map your item to a layout id based on a rule that you can define.

    So it is not exactly "group by", but you can use one layout for the group header and another one for each item of the group.

    public class TypeTemplateSelector : IMvxTemplateSelector
    {
        private readonly Dictionary<Type, int> _typeMapping;
    
        public TypeTemplateSelector()
        {
            _typeMapping = new Dictionary<Type, int>
            {
                {typeof(HeaderGroupViewModel), Resource.Layout.header_group},
                {typeof(GroupItemViewModel), Resource.Layout.group_item}
            };
        }
    
        public int GetItemViewType(object forItemObject)
        {
            return _typeMapping[forItemObject.GetType()];
        }
    
        public int GetItemLayoutId(int fromViewType)
        {
            return fromViewType;
        }
    }
    

    And in the axml you set it using the full qualified class name of the selector followed by the assembly name:

    <MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView               
                android:id="@+id/recyclerView"
                android:scrollbars="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:MvxItemTemplate="@layout/appointment_feed_item"
                app:MvxTemplateSelector="RecyclerViewDifferentTemplates.Droid.TypeTemplateSelector,RecyclerViewDifferentTemplates.Droid"
                app:MvxBind="ItemsSource Items" />
    

    Source and more info: RecyclerView TemplateSelector in MvvmCross

    HIH