Serhii Yaremych - Android developer, Master of Code Global
Я дам кілька порад, які точно стануть в нагоді. І Ви переконаєтесь, що працювати із безліччю viewType просто, а ItemDecorator не страшний.
for all views • Never ever use notifyItemRangeChanged() this way notifyItemRangeChanged(0, getItemsCount()) • Use DiffUtil to manage adapter updates Death 2: • Too many ViewHolders of the same type. How to fix:
to visualize dataset changes with animations. • Use DiffUtil. It handles all change calculations for you and dispatches them to the adapter • Use setHasStableIds(true) with getItemId(int position) and RecyclerView will automatically handle all animations on simple call notifyDataSetChanged()
adapters = new SparseArray<>(); private final List<ViewItem> items = new ArrayList<>(); private final ViewItem emptyItem = new ViewItem() {}; private final ViewItem progressItem = new ViewItem() {}; public MultiAdapter() { adapters.put(R.layout.header_item_layout, new HeaderItemsAdapter()); adapters.put(R.layout.common_item_layout, new CommonItemsAdapter()); adapters.put(R.layout.big_picture_item_layout, new BigPicturesAdapter()); adapters.put(R.layout.horizontall_item_layout, new HorizontalItemsAdapter()); adapters.put(R.layout.loading_item_layout, new ProgressItemAdapter()); adapters.put(R.layout.empty_item_layout, new EmptyItemAdapter()); // Add default item items.add(emptyItem); setHasStableIds(true); }
viewItems) {} @Override public long getItemId(int position) { return items.get(position).distinctId(); } @Override public int getItemViewType(int position) { return items.get(position).viewType(); }
firstHeader = new HeaderViewItem("Header 1") items.add(firstHeader); for (int i = 0; i < 5; i++) { // create common type items items.add(item); } final List < ColorItem > subHorizontalItems = new ArrayList<> (); for (int i = 0; i < 15; i++) { final ColorItem colorItem = new ColorItem(); subHorizontalItems.add(colorItem); } final HorizontalViewItem horizontalItem = new HorizontalViewItem("Horizontal item #1", subHorizontalItems); items.add(horizontalItem); final HeaderViewItem secondHeader = new HeaderViewItem("Header 2"); items.add(secondHeader); for (int i = 0; i < 3; i++) { // create big picture type item items.add(viewItem); } Wrap all items into our ViewItem models