Slide 1

Slide 1 text

RecyclerView: In & Out

Slide 2

Slide 2 text

Why RecyclerView?!

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

Item Decoration Adapter Recycled View Pool Layout Manager RecyclerView Item Animator Child Helper Adapter Helper Recycler

Slide 5

Slide 5 text

Pro RecyclerView RecyclerView Animations Worth watching videos

Slide 6

Slide 6 text

Components: ● RecyclerView ● Adapter ● LayoutManager ● ItemDecoration ● ItemAnimator ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 7

Slide 7 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter ● LayoutManager ● ItemDecoration ● ItemAnimator ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 8

Slide 8 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager ● ItemDecoration ● ItemAnimator ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 9

Slide 9 text

class MyAdapter extends RecyclerView.Adapter { public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { …... } public void onBindViewHolder(ItemHolder holder, int position) { …... } }

Slide 10

Slide 10 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration ● ItemAnimator ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 11

Slide 11 text

Adapter vs Layout Positions int getChildLayoutPosition(View child) {...} int getChildAdapterPosition(View child) {...}

Slide 12

Slide 12 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration provides decoration for items (DividerItemDecoration) ● ItemAnimator ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 13

Slide 13 text

ItemDecoration class ItemDecoration{ public void onDraw(Canvas c, RecyclerView parent, State state) {...} public void onDrawOver(Canvas c, RecyclerView parent, State state) {...} public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {...} }

Slide 14

Slide 14 text

ItemDecoration class ItemDecoration{ public void onDraw(Canvas c, RecyclerView parent, State state) {...} public void onDrawOver(Canvas c, RecyclerView parent, State state) {...} public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {...} }

Slide 15

Slide 15 text

Space evenly android:clipToPadding="false"

Slide 16

Slide 16 text

What if we want to customize the padding override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { //access view holder val viewHolder = parent.getChildViewHolder(view) val params = view.layoutParams as GridLayoutManager.LayoutParams val layoutManager = parent.layoutManager as GridLayoutManager //how much space view is occupied val spanSize = params.spanSize //number of spans in the grid val totalSpanSize = layoutManager.spanCount //position depends on the RTL val position = params.spanIndex ... }

Slide 17

Slide 17 text

What if we want to customize the padding override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) //access view holder val viewHolder = parent.getChildViewHolder(view) val params = view.layoutParams as GridLayoutManager.LayoutParams val layoutManager = parent.layoutManager as GridLayoutManager //how much space view is occupied val spanSize = params.spanSize //number of spans in the grid val totalSpanSize = layoutManager.spanCount //position depends on the RTL val position = params.spanIndex … }

Slide 18

Slide 18 text

What if we want to customize the padding override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) //access view holder val viewHolder = parent.getChildViewHolder(view) val params = view.layoutParams as GridLayoutManager.LayoutParams val layoutManager = parent.layoutManager as GridLayoutManager //how much space view is occupied val spanSize = params.spanSize //number of spans in the grid val totalSpanSize = layoutManager.spanCount //position depends on the RTL val position = params.spanIndex ... }

Slide 19

Slide 19 text

What if we want to customize the padding override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { … if ((spanSize + position) == total) { outRect.right = padding; } else if (position == 0) { outRect.left = padding; } else { outRect.left = padding; outRect.right = padding; } }

Slide 20

Slide 20 text

Is it right?!! Brrrr…...

Slide 21

Slide 21 text

What if we want to customize the padding override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val params = view.layoutParams as GridLayoutManager.LayoutParams val layoutManager = parent.layoutManager as GridLayoutManager val spanSize = params.spanSize val totalSpanSize = layoutManager.spanCount val position = params.spanIndex val n = (totalSpanSize / spanSize).toFloat() val percent = (position / spanSize).toFloat() val leftPadding = padding * ((n - percent) / n) val rightPadding = padding * ((percent + 1) / n) outRect.left = leftPadding.toInt() outRect.right = rightPadding.toInt() }

Slide 22

Slide 22 text

What if we want to customize the padding Phew, did it!!

Slide 23

Slide 23 text

Small question?

Slide 24

Slide 24 text

Solution GridLayoutManager(сontext, spanCount) But how wisely we can control the span size of each item? layouManager.spanSizeLookup = GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return (...) } }

Slide 25

Slide 25 text

ItemDecoration class ItemDecoration{ public void onDraw(Canvas c, RecyclerView parent, State state) {...} public void onDrawOver(Canvas c, RecyclerView parent, State state) {...} public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {...} }

Slide 26

Slide 26 text

override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val childCount = parent.childCount val manager = parent.layoutManager for (i in 0..childCount - 1) { val child = parent.get(i) val right = manager.getDecoratedRight(child) val left = manager.getDecoratedLeft(child) + paddingLeft val height = divider.intrinsicHeight ?: 0 val top = manager.getDecoratedBottom(child) val bottom = top + height divider.setBounds(left, top, right, bottom) divider.draw(c) } }

Slide 27

Slide 27 text

override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val childCount = parent.childCount val manager = parent.layoutManager for (i in 0..childCount - 1) { val child = parent.get(i) val right = manager.getDecoratedRight(child) val left = manager.getDecoratedLeft(child) + paddingLeft val height = divider.intrinsicHeight val top = manager.getDecoratedBottom(child) val bottom = top + height divider.setBounds(left, top, right, bottom) divider.draw(c) } }

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

Position override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { for (i in 0..childCount - 1) { val child = parent.get(i) parent.getChildAdapterPosition(child) } }

Slide 30

Slide 30 text

Position override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { for (i in 0..childCount - 1) { val child = parent.get(i) parent.getChildAdapterPosition(child) } } NO_POSITION while animating

Slide 31

Slide 31 text

Position override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { for (i in 0..childCount - 1) { val child = parent.get(i) parent.getChildLayoutPosition(child) } }

Slide 32

Slide 32 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration provides decoration for items (DividerItemDecoration) ● ItemAnimator defines the animations (DefaultItemAnimator) ● ItemTouchHelper ● SnapHelper ● DiffUtil

Slide 33

Slide 33 text

DefaultItemAnimator object :LinearLayoutManager(context) { override fun supportsPredictiveItemAnimations() return true }

Slide 34

Slide 34 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration provides decoration for items (DividerItemDecoration) ● ItemAnimator defines the animations (DefaultItemAnimator) ● ItemTouchHelper swipe-to-delete, drag&drop ● SnapHelper ● DiffUtil

Slide 35

Slide 35 text

val touchCallback = SwipeTouchCallback() val itemTouchHelper = ItemTouchHelper(touchCallback) itemTouchHelper.attachToRecyclerView(list)

Slide 36

Slide 36 text

class SwipeTouchCallback(private val callback: ItemTouchHelperAdapter) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START or ItemTouchHelper.END) { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { callback.onItemMove(viewHolder.adapterPosition, target.adapterPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { callback.onItemDismiss(viewHolder.adapterPosition) } }

Slide 37

Slide 37 text

class SwipeTouchCallback(private val callback: ItemTouchHelperAdapter) : ItemTouchHelper.SimpleCallback(0, 0) { override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {...} }

Slide 38

Slide 38 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration provides decoration for items (DividerItemDecoration) ● ItemAnimator defines the animations (DefaultItemAnimator) ● ItemTouchHelper swipe-to-delete, drag&drop ● SnapHelper LinearSnapHelper ● DiffUtil

Slide 39

Slide 39 text

Items with RecyclerView and horizontal LinearLayoutManager like CAROUSEL val snapHelper = LinearSnapHelper() snapHelper.attachToRecyclerView(this) LinearSnapHelper - Center snapping GravitySnapHelper(...): Gravity.START Gravity.END Gravity.BOTTOM Gravity.TOP rubensousa.github.io/2016/08/recyclerviewsnap

Slide 40

Slide 40 text

Revision 25.1.0 LinearLayoutManager. setInitialPrefetchItemCount(N) https://medium.com/google-developers/recyclerview-prefetch-c2f269075710

Slide 41

Slide 41 text

Components: ● RecyclerView creating, binding and recycling our views ● Adapter provides data (RecyclerView.Adapter) ● LayoutManager layouting and positioning (Linear/GridLayout managers) ● ItemDecoration provides decoration for items (DividerItemDecoration) ● ItemAnimator defines the animations (DefaultItemAnimator) ● ItemTouchHelper swipe-to-delete, drag&drop ● SnapHelper LinearSnapHelper ● DiffUtil compares, batches updates and invalidates adapter by positions

Slide 42

Slide 42 text

notifyItemChanged(…) notifyItemRangeChanged(…) notifyItemAdded(…) notifyItemRangeAdded(…) notifyItemRemoved(…) notifyItemRangeRemoved(…) notifyItemMoved(…) … and notifyChanged();

Slide 43

Slide 43 text

val diffResult = DiffUtil.calculateDiff( MyDiffCallback(bricks, newList)) //change adapter adapter.swapData(newList) //dispatch changes diffResult.dispatchUpdatesTo(adapter)

Slide 44

Slide 44 text

class MyDiffCallback(private var newBricks: List, private var oldBricks: List) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldBricks.size } override fun getNewListSize(): Int { return newBricks.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldBricks[oldItemPosition].id === newBricks[newItemPosition].id } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldBricks[oldItemPosition].equals(newBricks[newItemPosition]) } }

Slide 45

Slide 45 text

class MyDiffCallback(private var newBricks: List, private var oldBricks: List) : DiffUtil.Callback() { … override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any { return super.getChangePayload(oldItemPosition, newItemPosition) } } notifyItemChanged(int position, Object payload) notifyItemRangeChanged(int positionStart, int itemCount, Object payload)

Slide 46

Slide 46 text

Холливар Multiple View Types

Slide 47

Slide 47 text

Naïve way public class ViewTypes { private static final int VIEW_TYPE_NORMAL = 0; private static final int VIEW_TYPE_SUBHEADER = 1; private static final int VIEW_TYPE_SEPARATOR = 2; private static final int VIEW_TYPE_HEADER = 3; }

Slide 48

Slide 48 text

Naïve way @Override public int getItemViewType(int position) { NavigationMenuItem item = mItems.get(position); if (item instanceof NavigationMenuSeparatorItem) { return VIEW_TYPE_SEPARATOR; } else if (item instanceof NavigationMenuHeaderItem) { return VIEW_TYPE_HEADER; } else if (item instanceof NavigationMenuTextItem) { NavigationMenuTextItem textItem = (NavigationMenuTextItem) item; if (textItem.getMenuItem().hasSubMenu()) { return VIEW_TYPE_SUBHEADER; } else { return VIEW_TYPE_NORMAL; } } throw new RuntimeException("Unknown item type."); }

Slide 49

Slide 49 text

Naïve way - item creation @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_NORMAL: return new NormalViewHolder(mLayoutInflater, parent, mOnClickListener); case VIEW_TYPE_SUBHEADER: return new SubheaderViewHolder(mLayoutInflater, parent); case VIEW_TYPE_SEPARATOR: return new SeparatorViewHolder(mLayoutInflater, parent); case VIEW_TYPE_HEADER: return new HeaderViewHolder(mHeaderLayout); } return null; }

Slide 50

Slide 50 text

Binding @Override public void onBindViewHolder(ViewHolder holder, int position) { switch (getItemViewType(position)) { case VIEW_TYPE_NORMAL: { NavigationMenuItemView itemView = (NavigationMenuItemView) holder.itemView; ... break; } case VIEW_TYPE_SUBHEADER: { TextView subHeader = (TextView) holder.itemView; NavigationMenuTextItem item = (NavigationMenuTextItem) mItems.get(position); ... break; } case VIEW_TYPE_SEPARATOR: case VIEW_TYPE_HEADER: ... } }

Slide 51

Slide 51 text

After implementation

Slide 52

Slide 52 text

Solutions - Favor composition over inheritance interface AdapterDelegate { fun isForViewType(items: T, position: Int): Boolean fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder fun onBindViewHolder(items: T, position: Int, holder: RecyclerView.ViewHolder) }

Slide 53

Slide 53 text

Solutions - Favor composition over inheritance class NewsTipAdapter : RecyclerView.Adapter{ var delegates: MutableList() init{ delegates.add(NewsTeaserAdapterDelegate()) // Assigns internally ViewType integer delegates.add(PetFoodTipAdapterDelegate()) } .... }

Slide 54

Slide 54 text

Solutions - Favor composition over inheritance class NewsTipAdapter : RecyclerView.Adapter() { ... override fun onBindViewHolder(holder: VH, position: Int) { delegates.forEach { if (it.isForViewType(items, position)) { // Main concern here it.onBindViewHolder(items, position, holder) return@forEach } } } }

Slide 55

Slide 55 text

Composition class CatAdapterDelegate() : AdapterDelegate>() { protected fun isForViewType(items: List, position: Int): Boolean { return items[position] is Cat } } http://hannesdorfmann.com/android/adapter-delegates

Slide 56

Slide 56 text

Epoxy https://github.com/airbnb/epoxy https://medium.com/airbnb-engineering/epoxy-airbnbs-view-architecture-on-android-c3e1af150394

Slide 57

Slide 57 text

Epoxy class HeaderModel : EpoxyModel() { var city: City fun bind(headerView: HeaderView) { headerView.setImage(city.getImage()) headerView.setTitle(city.getName()) headerView.setDescription(city.getDescription()) } val defaultLayout: Int @LayoutRes get() = R.layout.model_header_view }

Slide 58

Slide 58 text

Epoxy class HeaderModel : EpoxyModel() { var city: City fun bind(headerView: HeaderView) { headerView.setImage(city.getImage()) headerView.setTitle(city.getName()) headerView.setDescription(city.getDescription()) } val defaultLayout: Int @LayoutRes get() = R.layout.model_header_view }

Slide 59

Slide 59 text

Epoxy class HeaderModel : EpoxyModel() { var city: City fun bind(headerView: HeaderView) { headerView.setImage(city.getImage()) headerView.setTitle(city.getName()) headerView.setDescription(city.getDescription()) } val defaultLayout: Int @LayoutRes get() = R.layout.model_header_view }

Slide 60

Slide 60 text

Epoxy class HeaderModel : EpoxyModel() { var city: City fun bind(headerView: HeaderView) { headerView.setImage(city.getImage()) headerView.setTitle(city.getName()) headerView.setDescription(city.getDescription()) } val defaultLayout: Int @LayoutRes get() = R.layout.model_header_view }

Slide 61

Slide 61 text

Visitor interface ViewVisitor { fun type(typeFactory: TypeFactory): Int }

Slide 62

Slide 62 text

Factory interface TypeFactoryImpl : TypeFactory { fun type(category: CategoryVisitor): Int fun type(categoryMovie: OverviewCategoryMovieVisitor): Int fun type(space: OverviewSpaceVisitor): Int fun type(movie: MoviesMovieVisitor): Int }

Slide 63

Slide 63 text

interface TypeFactory { fun holder(type: Int, view: View): AdapterViewHolder<*> } ... class TypeFactoryImpl : TypeFactory { override fun type(category: CategoryVisitor) = R.layout.li_vod_category override fun holder(type: Int, view: View): AdapterViewHolder<*> { return when (type) { R.layout.li_vod_category -> CategoryHolder(view) R.layout.li_vod_overview_category_movie -> OverviewCategoryMovieHolder(view) R.layout.v_li_space_horizontal -> OverviewSpaceHolder(view) R.layout.li_vod_movie -> MoviesMovieHolder(view) else -> throw RuntimeException("Illegal view type") } } }

Slide 64

Slide 64 text

interface TypeFactory { fun holder(type: Int, view: View): AdapterViewHolder<*> } ... class TypeFactoryImpl : TypeFactory { override fun type(category: CategoryVisitor) = R.layout.li_vod_category override fun holder(type: Int, view: View): AdapterViewHolder<*> { return when (type) { R.layout.li_vod_category -> CategoryHolder(view) R.layout.li_vod_overview_category_movie -> OverviewCategoryMovieHolder(view) R.layout.v_li_space_horizontal -> OverviewSpaceHolder(view) R.layout.li_vod_movie -> MoviesMovieHolder(view) else -> throw RuntimeException("Illegal view type") } } }

Slide 65

Slide 65 text

abstract class AdapterViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun bind(item: T, position: Int) abstract fun recycled(holder: AdapterViewHolder<*>) } class VodMoviesMovieVisitor(val movie: MovieDisplayObject) : VodViewVisitor { override fun type(typeFactory: VodTypeFactory): Int = typeFactory.type(this) } class VodMoviesMovieHolder(view: View) : SimpleAdapterViewHolder(view) { ... override fun bind(item: VodMoviesMovieVisitor, position: Int) { .. } }

Slide 66

Slide 66 text

abstract class AdapterViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun bind(item: T, position: Int) abstract fun recycled(holder: AdapterViewHolder<*>) } class VodMoviesMovieVisitor(val movie: MovieDisplayObject) : VodViewVisitor { override fun type(typeFactory: VodTypeFactory): Int = typeFactory.type(this) } class VodMoviesMovieHolder(view: View) : SimpleAdapterViewHolder(view) { ... override fun bind(item: VodMoviesMovieVisitor, position: Int) { .. } }

Slide 67

Slide 67 text

abstract class AdapterViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun bind(item: T, position: Int) abstract fun recycled(holder: AdapterViewHolder<*>) } class VodMoviesMovieVisitor(val movie: MovieDisplayObject) : VodViewVisitor { override fun type(typeFactory: VodTypeFactory): Int = typeFactory.type(this) } class VodMoviesMovieHolder(view: View) : SimpleAdapterViewHolder(view) { ... override fun bind(item: VodMoviesMovieVisitor, position: Int) { .. } }

Slide 68

Slide 68 text

abstract class AdapterViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun bind(item: T, position: Int) abstract fun recycled(holder: AdapterViewHolder<*>) } class VodMoviesMovieVisitor(val movie: MovieDisplayObject) : VodViewVisitor { override fun type(typeFactory: VodTypeFactory): Int = typeFactory.type(this) } class VodMoviesMovieHolder(view: View) : SimpleAdapterViewHolder(view) { ... override fun bind(item: VodMoviesMovieVisitor, position: Int) { .. } }

Slide 69

Slide 69 text

Read&watch ● https://www.youtube.com/watch?v=imsr8NrIAMs ● https://realm.io/news/360andev-yigit-boyar-pro-recyclerview-android-ui-java/ ● http://frogermcs.github.io/recyclerview-animations-androiddevsummit-write-up/ ● http://hannesdorfmann.com/android/adapter-delegates ● https://medium.com/@nullthemall/diffutil-is-a-must-797502bc1149#.28n56v7zr ● https://medium.com/@dpreussler/writing-better-adapters-1b09758407d2#.9vzaoxz5e ● http://www.devexchanges.info/2016/09/android-tip-recyclerview-snapping-with.html ● https://guides.codepath.com/android/using-the-recyclerview ● https://medium.com/@ipaulpro/drag-and-swipe-with-recyclerview-b9456d2b1aaf

Slide 70

Slide 70 text

Certificate of achievement awarded to Attendees for outstanding knowledge on RecyclerView

Slide 71

Slide 71 text

Feedback https://goo.gl/2upLcm