recyclerview adapter multiple view types

Solutions on MaxInterview for recyclerview adapter multiple view types by the best coders in the world

showing results for - "recyclerview adapter multiple view types"
Emma
18 Mar 2020
1public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
2    class ViewHolder0 extends RecyclerView.ViewHolder {
3        ...
4        public ViewHolder0(View itemView){
5        ...
6        }
7    }
8
9    class ViewHolder2 extends RecyclerView.ViewHolder {
10        ...
11        public ViewHolder2(View itemView){
12        ...
13    }
14
15    @Override
16    public int getItemViewType(int position) {
17        // Just as an example, return 0 or 2 depending on position
18        // Note that unlike in ListView adapters, types don't have to be contiguous
19        return position % 2 * 2;
20    }
21
22    @Override
23    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
24         switch (viewType) {
25             case 0: return new ViewHolder0(...);
26             case 2: return new ViewHolder2(...);
27             ...
28         }
29    }
30
31    @Override
32    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
33        switch (holder.getItemViewType()) {
34            case 0:
35                ViewHolder0 viewHolder0 = (ViewHolder0)holder;
36                ...
37                break;
38
39            case 2:
40                ViewHolder2 viewHolder2 = (ViewHolder2)holder;
41                ...
42                break;
43        }
44    }
45}