SlideShare a Scribd company logo
thagikura
Deep Dive Into LayoutManager 

for RecyclerView
$ whoami
Takeshi Hagikura
@thagikura


Developer Relations

@Google
RecyclerView
RecyclerView
Adapter
Recycler
LayoutManager
ItemDecoration
ItemAnimator
RecycledViewPool
TouchHelper
DiffUtil



LinearLayoutManager
GridLayoutManager
StaggeredGridLayoutManager
Is it possible to add a
custom LayoutManager?
FlexboxLayoutManager
github.com/google/flexbox-layout
Ports Flexbox in CSS to Android
How to create a
custom LayoutManager?
Think before you build it
Much harder than custom view
Gives you much flexibility
on top of RecyclerView features
Deep Dive Into LayoutManager for RecyclerView
At the bare minimum,
need to override…
onLayoutChildren
Called on:
- initial layout
- adapter changes
Lay out all relevant child views
Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerView
If this isViewGroup
(except RecyclerView)
All child views on memory
In RecyclerView +
LayoutManager
Only visible views should
be on memory
onLayoutChildren
1. Find the anchor position
Anchor position
Starting position to put views.
Start with 0 on initial layout.



Remember the first visible view to
restore the state
onLayoutChildren
1. Find the anchor position
2. Calculate how many items

should be in visible portion
onLayoutChildren
1. Find the anchor position
2. Calculate how many items

should be in visible portion
3. Fill toward end
private int fill(RecyclerView.Recycler recycler,
RecyclerView.State state,
LayoutState layoutState) {
int start = layoutState.mAvailable;
int remainingSpace = layoutState.mAvailable;
int consumed = 0;
while (remainingSpace > 0 &&
layoutState.hasMore(state, mFlexLines)) {
FlexLine flexLine =
mFlexLines.get(layoutState.mFlexLinePosition);
layoutState.mPosition = flexLine.mFirstIndex;
consumed += layoutFlexLine(flexLine, layoutState);
remainingSpace -= flexLine.getCrossSize();
}
layoutState.mAvailable -= consumed;
return start - layoutState.mAvailable;
}
Simplified version of fill
private int fill(RecyclerView.Recycler recycler,
RecyclerView.State state,
LayoutState layoutState) {
int start = layoutState.mAvailable;
int remainingSpace = layoutState.mAvailable;
int consumed = 0;
while (remainingSpace > 0 &&
layoutState.hasMore(state, mFlexLines)) {
FlexLine flexLine =
mFlexLines.get(layoutState.mFlexLinePosition);
layoutState.mPosition = flexLine.mFirstIndex;
consumed += layoutFlexLine(flexLine, layoutState);
remainingSpace -= flexLine.getCrossSize();
}
layoutState.mAvailable -= consumed;
return start - layoutState.mAvailable;
}
mAvailable: Amount of pixels need to be filled
mDirection: START | END
private int fill(RecyclerView.Recycler recycler,
RecyclerView.State state,
LayoutState layoutState) {
int start = layoutState.mAvailable;
int remainingSpace = layoutState.mAvailable;
int consumed = 0;
while (remainingSpace > 0 &&
layoutState.hasMore(state, mFlexLines)) {
FlexLine flexLine =
mFlexLines.get(layoutState.mFlexLinePosition);
layoutState.mPosition = flexLine.mFirstIndex;
consumed += layoutFlexLine(flexLine, layoutState);
remainingSpace -= flexLine.getCrossSize();
}
layoutState.mAvailable -= consumed;
return start - layoutState.mAvailable;
}
Put views and
loop until mAvailable < 0
onLayoutChildren
1. Find the anchor position
2. Calculate how many items

should be in visible portion
3. Fill toward end
4. Fill toward start
Why fill toward both directions?
In some cases anchor position may
be at the bottom
1 2
3
4 5
6 7
8 9
10
11
scrollToPosition(50)
42 43
44
45
46 47
48
49 50
Anchor position
scrollVerticallyBy
Interact with scroll by the user
@Override
public boolean canScrollVertically() {
return true;
}
Could be false depending on attributes.
E.g. Orientation in LinearLayoutManager
@Override
public int scrollVerticallyBy(int dy, 

RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (isMainAxisDirectionHorizontal()) {
int scrolled = 

handleScrollingCrossAxis(dy, recycler, state);
mViewCache.clear();
return scrolled;
} else {
int scrolled = handleScrollingMainAxis(dy);
mAnchorInfo.mPerpendicularCoordinate += scrolled;
mSubOrientationHelper.offsetChildren(-scrolled);
return scrolled;
}
}
@Override
public int scrollVerticallyBy(int dy, 

RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (isMainAxisDirectionHorizontal()) {
int scrolled = 

handleScrollingCrossAxis(dy, recycler, state);
mViewCache.clear();
return scrolled;
} else {
int scrolled = handleScrollingMainAxis(dy);
mAnchorInfo.mPerpendicularCoordinate += scrolled;
mSubOrientationHelper.offsetChildren(-scrolled);
return scrolled;
}
}
Distance to scroll in pixels
@Override
public int scrollVerticallyBy(int dy, 

RecyclerView.Recycler recycler,
RecyclerView.State state) {
if (isMainAxisDirectionHorizontal()) {
int scrolled = 

handleScrollingCrossAxis(dy, recycler, state);
mViewCache.clear();
return scrolled;
} else {
int scrolled = handleScrollingMainAxis(dy);
mAnchorInfo.mPerpendicularCoordinate += scrolled;
mSubOrientationHelper.offsetChildren(-scrolled);
return scrolled;
}
}
The actual distance scrolled
Small dy
Only shift existing views
mRecyclerView.offsetChildrenVertical(dy);
Large dy
Large dy
Recycle views no
longer visible
Large dy
Fill appearing views
What does Recycle mean?
Two types of cache
in RecyclerView
1. Recycle
2. Scrap
Recycler
RecycledViewPool
1. Recycle
Recycler
RecycledViewPool
LayoutManager
recycler.recycleView(View)
1. Recycle
Recycler
RecycledViewPool
LayoutManager
recycler.recycleView(View)
1. Recycle
Considered as dirty
RecyclerRecycler
RecycledViewPool
Can be shared across multiple RecyclerViews
Recycler
Scrap Heap
2. Scrap
Recycler
Scrap Heap
LayoutManager
recycler.scrapView(View)
2. Scrap
Recycler
Scrap Heap
LayoutManager
detachAndScrapAttachedViews
RecyclerView
recycler.scrapView(View)
2. Scrap
How to retrieve aView?
LayoutManager Adapter
Recycler
recycler.getViewForPosition(int)
Case1. Found in scrap
Case2. Found in Recycled Pool
Case3. Not found in cache
LayoutManager Adapter
Recycler
Case1. Found in scrap
LayoutManager Adapter
Recycler
Case2. Found in Recycled Pool
adapter.bindViewHolder
LayoutManager Adapter
Recycler
Case2. Found in Recycled Pool
LayoutManager Adapter
Recycler
Case3. Not found in cache
adapter.createViewHolder
LayoutManager Adapter
Recycler
Case3. Not found in cache
Use scrap if you re-attach in a
same layout pass
Use recycle for views no longer
needed
scrollHorizontallyBy
Same with vertical except for the
direction
Now you implement basic functions.
Is it enough?
Could be useable... but NO.
scrollTo(position)
smoothScrollTo(position)
Fast Scrolling
Item Decorations
Item prefetch
Predictive Animations
There are a lot more…
scrollTo(position)
smoothScrollTo(position)
Fast Scrolling
Item Decorations
Item prefetch
Predictive Animations
There are a lot more…
Predictive Animations
Off OnAdd aView
Off OnDelete aView
@Override
public boolean supportsPredictiveItemAnimations() {
return true;
}
onLayoutChildren
Real Layout
Pre-layout
In pre-layout
Lay out all the views currently visible and
additional views that are appearing (or
disappearing) after the animation
Pre-layout
Remaining
Appearing
Disappearing
To be inserted
at this positionVisible area
Real-layout
Remaining
Appearing
Disappearing
Visible area
Pre-layout
Remaining
Appearing
Disappearing
To be deletedVisible area
Real layout
Remaining
Appearing
Disappearing
Visible area
Now you know the basics of
building a custom LayoutManager
Resources
Source of default LayoutManagers


github.com/google/flexbox-layout


wiresareobsolete.com/2014/09/building-a-recyclerview-
layoutmanager-part-1/

Thank you!
Takeshi Hagikura
@thagikura

More Related Content

PDF
Mastering the Retail Omni Channel Experience with Aldo, Salesforce & Traction...
PPTX
Block chain technology
PDF
The Zenon Deck.pdf
PDF
How blockchain technology works in healthcare industry
PDF
Mastering RecyclerView Layouts
ODP
Android App Development - 04 Views and layouts
PDF
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
PDF
How to use redux with react hooks in react native application
Mastering the Retail Omni Channel Experience with Aldo, Salesforce & Traction...
Block chain technology
The Zenon Deck.pdf
How blockchain technology works in healthcare industry
Mastering RecyclerView Layouts
Android App Development - 04 Views and layouts
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
How to use redux with react hooks in react native application

Similar to Deep Dive Into LayoutManager for RecyclerView (20)

PDF
Recompacting your react application
PDF
What's new in android: jetpack compose 2024
PDF
Android UI Development: Tips, Tricks, and Techniques
PDF
Android UI Tips, Tricks and Techniques
PDF
Enhancing UI/UX using Java animations
PDF
Building Apps with Flutter - Hillel Coren, Invoice Ninja
PDF
Recoil at Codete Webinars #3
PDF
Improving android experience for both users and developers
PDF
Droidcon2013 android experience lahoda
PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
PDF
React Native Androidはなぜ動くのか
PPTX
Adaptive UI - 解像度の異なるデバイスや画面の向きに対応する 最適なレイアウトへ -
PPTX
Android 3
PDF
Optimize CollectionView Scrolling
PDF
Android Best Practices
PDF
Introduction to React Native Workshop
PDF
Workshop 25: React Native - Components
PDF
Materi Modern React Redux Power Point.pdf
PDF
Maps - Part 3 - Transcript.pdf
PPTX
Architecting Single Activity Applications (With or Without Fragments)
Recompacting your react application
What's new in android: jetpack compose 2024
Android UI Development: Tips, Tricks, and Techniques
Android UI Tips, Tricks and Techniques
Enhancing UI/UX using Java animations
Building Apps with Flutter - Hillel Coren, Invoice Ninja
Recoil at Codete Webinars #3
Improving android experience for both users and developers
Droidcon2013 android experience lahoda
Workshop 20: ReactJS Part II Flux Pattern & Redux
React Native Androidはなぜ動くのか
Adaptive UI - 解像度の異なるデバイスや画面の向きに対応する 最適なレイアウトへ -
Android 3
Optimize CollectionView Scrolling
Android Best Practices
Introduction to React Native Workshop
Workshop 25: React Native - Components
Materi Modern React Redux Power Point.pdf
Maps - Part 3 - Transcript.pdf
Architecting Single Activity Applications (With or Without Fragments)
Ad

Recently uploaded (20)

PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Well-logging-methods_new................
PPT
Project quality management in manufacturing
PPTX
Welding lecture in detail for understanding
PPT
Mechanical Engineering MATERIALS Selection
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
PPT on Performance Review to get promotions
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Well-logging-methods_new................
Project quality management in manufacturing
Welding lecture in detail for understanding
Mechanical Engineering MATERIALS Selection
R24 SURVEYING LAB MANUAL for civil enggi
Embodied AI: Ushering in the Next Era of Intelligent Systems
Foundation to blockchain - A guide to Blockchain Tech
Automation-in-Manufacturing-Chapter-Introduction.pdf
UNIT 4 Total Quality Management .pptx
OOP with Java - Java Introduction (Basics)
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT on Performance Review to get promotions
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Ad

Deep Dive Into LayoutManager for RecyclerView