android - What is the best way to have different Objects in a recycler view? -


my recycler view list of data youtube api using gson library. in 1 url, returned json :

items: [ { kind: "youtube#playlist", etag: ""tag/abc"", id: "id",  

notice id field string

the problem is, other url return :

items: [ { kind: "youtube#searchresult", etag: ""etag/abc"", id: { kind: "youtube#playlist", playlistid: "id" }, 

the id become class.

the simplest way create different gson models , different adapter recycler view. need call setadapter multiple time, impact performance.

do have better workaround this?

thanks time

you don't need create multiple recyclerview.adapter. recyclerview , listview can act same using @override getitemviewtype(int position).

see documentation here.

in adapter:
1. @override getitemviewtype(int position). return final static int representing view type (like 1 or 0)
2. inflate correct view in oncreateviewholder(viewgroup parent, int viewtype) viewtype.
3. in onbindviewholder manage object type.

extended example adapter:

public class messageadapter extends recyclerview.adapter<messageadapter.viewholder> {      public static final int view_type_normal = 0;     public static final int view_type_footer = 1;      private linkedlist<message> mdataset = new linkedlist<>();      @override     public viewholder oncreateviewholder(viewgroup parent, int viewtype) {         view v;         // assume have same viewholder, prefer use 2 different viewholder make more sense         if (viewtype == view_type_footer) {             v = layoutinflater.from(parent.getcontext())                     .inflate(r.layout.item_message_footer, parent, false);         } else {             v = layoutinflater.from(parent.getcontext())                     .inflate(r.layout.item_message, parent, false);         }         return new viewholder(v);     }       @override     public int getitemviewtype(int position) {         // define here rule change view type according position , data         return (position == mdataset.size()) ? view_type_footer : view_type_normal;     }      @override     public void onbindviewholder(viewholder holder, int position) {         // check position or instance of holder , change view data     } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -