android - How to create RecyclerView with multiple view type? -


from https://developer.android.com/preview/material/ui-widgets.html

when creating recyclerview.adapter have specify viewholder bind adapter.

public class myadapter extends recyclerview.adapter<myadapter.viewholder> {      private string[] mdataset;      public myadapter(string[] mydataset) {         mdataset = mydataset;     }      public static class viewholder extends recyclerview.viewholder {         public textview mtextview;         public viewholder(textview v) {             super(v);             mtextview = v;         }     }      @override     public myadapter.viewholder oncreateviewholder(viewgroup parent, int viewtype) {         view v = layoutinflater.from(parent.getcontext()).inflate(r.layout.some_layout, parent, false);          //findviewbyid...          viewholder vh = new viewholder(v);         return vh;     }      @override     public void onbindviewholder(viewholder holder, int position) {         holder.mtextview.settext(mdataset[position]);     }      @override     public int getitemcount() {         return mdataset.length;     } } 

so, possible create recyclerview multiple view type?

yes, it's possible. implement getitemviewtype(), , take care of viewtype parameter in oncreateviewholder().

so like:

public class myadapter extends recyclerview.adapter<recyclerview.viewholder> {     class viewholder0 extends recyclerview.viewholder {         ...         public viewholder0(view itemview){         ...         }     }      class viewholder2 extends recyclerview.viewholder {         ...         public viewholder2(view itemview){         ...     }      @override     public int getitemviewtype(int position) {         // example, return 0 or 2 depending on position         // note unlike in listview adapters, types don't have contiguous         return position % 2 * 2;     }      @override     public recyclerview.viewholder oncreateviewholder(viewgroup parent, int viewtype) {          switch (viewtype) {              case 0: return new viewholder0(...);              case 2: return new viewholder2(...);              ...          }     }      @override     public void onbindviewholder(final recyclerview.viewholder holder, final int position) {         switch (holder.getitemviewtype()) {             case 0:                 viewholder0 viewholder0 = (viewholder0)holder;                 ...                 break;              case 2:                 viewholder2 viewholder2 = (viewholder2)holder;                 ...                 break;         }     } } 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -