SlideShare a Scribd company logo
1 of 29
Download to read offline
Mastering RecyclerView Layouts
Dave Smith • NewCircle, Inc.
@devunwired
+DaveSmithDev
Why Am I Here?
Help Reduce Sanitarium Admissions
caused by RecyclerView Layouts.
RecyclerView recyclerView = new RecyclerView(this);

recyclerView.setLayoutManager(…);



setContentView(recyclerView);
LinearLayoutManager
LinearLayoutManager manager = new LinearLayoutManager(

this,

LinearLayoutManager.VERTICAL,

false);
GridLayoutManager
GridLayoutManager manager = new GridLayoutManager(
this,

2, /* Number of grid columns */

GridLayoutManager.VERTICAL,

false);
GridLayoutManager
GridLayoutManager manager = new GridLayoutManager(
this,

2, /* Number of grid columns */

GridLayoutManager.VERTICAL,

false);
manager.setSpanSizeLookup(

new GridLayoutManager.SpanSizeLookup() {

@Override

public int getSpanSize(int position) {

//Stagger every other row

return (position % 3 == 0 ? 2 : 1);

}

});
StaggeredGridLayoutManager
StaggeredGridLayoutManager manager =
new StaggeredGridLayoutManager(

2, /* Number of grid columns */

StaggeredGridLayoutManager.VERTICAL);
Case Study: FixedGridLayoutManager
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
The Recycler
LayoutManager Recycler
Adapter
Obtain View
Recycle View
Bind
The Recycler
LayoutManager Recycler
Adapter
Obtain View
Recycle View
Bind
The Recycler
Scrap Heap
detachAndScrapView()
Recycle Pool
removeAndRecycleView()
Handling Decorations
Item View
getDecoratedLeft()
getDecoratedTop()
getDecoratedRight()
getDecoratedBottom()
Handling Decorations
Item View
getDecoratedWidth()
getDecoratedHeight()
Handling Decorations
Item View
layoutDecorated()
measureChild()
The Fill Technique
fillGaps()
Discover first visible position/location
Find layout gaps (at the edges)
Scrap everything
Lay out all visible positions
Save as little
state as possible.
Is there space before the first visible position?
Is there space after the last visible position?
The Fill Technique
private void fillGrid(int direction, …,

RecyclerView.Recycler recycler,

RecyclerView.State state) {

//…Obtain the first visible item position…


detachAndScrapAttachedViews(recycler);



for (…) {

int nextPosition = …;



View View = recycler.getViewForPosition(nextPosition);
addView(view);



measureChildWithMargins(view, …);

layoutDecorated(view, …);

}



private void fillGrid(int direction, …,

RecyclerView.Recycler recycler,

RecyclerView.State state) {

//…Obtain the first visible item position…


detachAndScrapAttachedViews(recycler);



for (…) {

int nextPosition = …;



View View = recycler.getViewForPosition(nextPosition);
addView(view);



measureChildWithMargins(view, …);

layoutDecorated(view, …);

}



//Remove anything that is left behind
final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList();

for (int i=0; i < scrapList.size(); i++) {

final View removingView = scrapList.get(i);

recycler.recycleView(removingView);

}

}
0 1
2 3
4 5
6 7
Use Attach/
Detach to quickly
reorder view
indices.
Level 1: Make It Work
onLayoutChildren()
Run a FILL operation
canScrollVertically()
canScrollHorizontally()
Which axes enable scrolling?
scrollHorizontallyBy()
scrollVerticallyBy()
Clamp supplied delta against boundary conditions
Shift all views in the layout
Trigger a FILL operation
Report back actual distance scrolled
Level 1: Make It Work
public int scrollHorizontallyBy(int dx,
RecyclerView.Recycler recycler, RecyclerView.State state) {

…



int delta;

if (dx > 0) { // Contents are scrolling left

delta = …;

} else { // Contents are scrolling right

delta = …;

}



offsetChildrenHorizontal(delta);



if (dx > 0) {

fillGrid(DIRECTION_START, …, recycler, state);

} else {

fillGrid(DIRECTION_END, …, recycler, state);

}



return -delta;

}
Level 2: Data Set Changes
onAdapterChanged()
removeAllViews()
notifyDataSetChanged() -> onLayoutChanged()
Treat as a new layout, and just run a FILL…
Level 3: Add Some Flair
scrollToPosition()
Track Requested Position
Trigger requestLayout()
smoothScrollToPosition()
Create a SmoothScroller instance
Set the target position
Invoke startSmoothScroll()
Level 3: Add Some Flair
LinearSmoothScroller scroller =
new LinearSmoothScroller(recyclerView.getContext()) {



@Override

public PointF computeScrollVectorForPosition(int targetPosition) {

final int rowOffset = …;

final int columnOffset = …;



return new PointF(columnOffset * stepWidth,
rowOffset * stepHeight);

}

};


scroller.setTargetPosition(position);

startSmoothScroll(scroller);
Level 4: Zen Master
supportsPredictiveItemAnimations()
We have more to say about animations…
onLayoutChildren() [isPreLayout() == true]
Note any removed views -> LayoutParams.isViewRemoved()
Add extra views during FILL to cover space left behind
onLayoutChildren()
Place disappearing views off-screen
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {

…


if (state.isPreLayout()) {

final View child = getChildAt(…);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();

if (lp.isItemRemoved()) { //Track and count view removals… }

}



//Clear all attached views into the recycle bin

detachAndScrapAttachedViews(recycler);



//Fill the grid for the initial layout of views

fillGrid(…);



//Anything left? Lay out for disappearing animation

if (!state.isPreLayout() && !recycler.getScrapList().isEmpty()) {

final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList();

//Laying out a scrap item removes it from the list…
//Beware concurrent modification!


…

}

}
Default Item Animations
Predictive Item Animations
Resources
RecyclerView Playground
https://github.com/devunwired/recyclerview-playground
Building a RecyclerView LayoutManager
http://wiresareobsolete.com/
Redux - Handling Disconnected Ranges
Android SDK Reference
https://developer.android.com/training/material/lists-cards.html

More Related Content

What's hot

What's hot (20)

ReactJS
ReactJSReactJS
ReactJS
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveDataAndroid MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
React Context API
React Context APIReact Context API
React Context API
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Android activities & views
Android activities & viewsAndroid activities & views
Android activities & views
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
React hooks
React hooksReact hooks
React hooks
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Android UI
Android UIAndroid UI
Android UI
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 

Viewers also liked

Master of RecyclerView
Master of RecyclerViewMaster of RecyclerView
Master of RecyclerView
Yuki Anzai
 
Android 02 - Recycler View Adapter
Android 02 - Recycler View AdapterAndroid 02 - Recycler View Adapter
Android 02 - Recycler View Adapter
Aline Borges
 

Viewers also liked (20)

Build and Distributing SDK Add-Ons
Build and Distributing SDK Add-OnsBuild and Distributing SDK Add-Ons
Build and Distributing SDK Add-Ons
 
Master of RecyclerView
Master of RecyclerViewMaster of RecyclerView
Master of RecyclerView
 
ExtraLayoutSpace of RecyclerView
ExtraLayoutSpace of RecyclerViewExtraLayoutSpace of RecyclerView
ExtraLayoutSpace of RecyclerView
 
Fun with RecyclerView
Fun with RecyclerViewFun with RecyclerView
Fun with RecyclerView
 
Tech Talk #2: Android app performance tips
Tech Talk #2: Android app performance tipsTech Talk #2: Android app performance tips
Tech Talk #2: Android app performance tips
 
The Tale of a Smooth RecyclerView
The Tale of a Smooth RecyclerViewThe Tale of a Smooth RecyclerView
The Tale of a Smooth RecyclerView
 
More Android UIs
More Android UIsMore Android UIs
More Android UIs
 
Infinum Android Talks #09 - UI optimization
Infinum Android Talks #09 - UI optimization Infinum Android Talks #09 - UI optimization
Infinum Android Talks #09 - UI optimization
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
Food Waste Recycling Education - Obeo
Food Waste Recycling Education - ObeoFood Waste Recycling Education - Obeo
Food Waste Recycling Education - Obeo
 
Zero waste action plan 2010
Zero waste action plan 2010Zero waste action plan 2010
Zero waste action plan 2010
 
Write cleaner, maintainable, and testable code in Android with MVVM
Write cleaner, maintainable, and testable code in Android with MVVMWrite cleaner, maintainable, and testable code in Android with MVVM
Write cleaner, maintainable, and testable code in Android with MVVM
 
Bonnes pratiques développement android
Bonnes pratiques développement androidBonnes pratiques développement android
Bonnes pratiques développement android
 
Android 02 - Recycler View Adapter
Android 02 - Recycler View AdapterAndroid 02 - Recycler View Adapter
Android 02 - Recycler View Adapter
 
Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)
 
Tutorial android - créer des apps
Tutorial android - créer des appsTutorial android - créer des apps
Tutorial android - créer des apps
 
The shawshank redemption review
The shawshank redemption reviewThe shawshank redemption review
The shawshank redemption review
 
Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2
Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2
Architecture et Bonnes pratiques Android #DevoxxFr2016 Part2
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
droidgirls Recyclerview
droidgirls Recyclerviewdroidgirls Recyclerview
droidgirls Recyclerview
 

Similar to Mastering RecyclerView Layouts

Value isnt changing and I cant seem to get the conversion to wor.pdf
Value isnt changing and I cant seem to get the conversion to wor.pdfValue isnt changing and I cant seem to get the conversion to wor.pdf
Value isnt changing and I cant seem to get the conversion to wor.pdf
amirthagiftsmadurai
 

Similar to Mastering RecyclerView Layouts (20)

Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewDeep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerView
 
2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
 
Building Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice NinjaBuilding Apps with Flutter - Hillel Coren, Invoice Ninja
Building Apps with Flutter - Hillel Coren, Invoice Ninja
 
Prescribing RX Responsibly
Prescribing RX ResponsiblyPrescribing RX Responsibly
Prescribing RX Responsibly
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Diaconu andrei list view vs recyclerview in android l
Diaconu andrei   list view vs recyclerview in android lDiaconu andrei   list view vs recyclerview in android l
Diaconu andrei list view vs recyclerview in android l
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
MVI - Managing State The Kotlin Way
MVI - Managing State The Kotlin WayMVI - Managing State The Kotlin Way
MVI - Managing State The Kotlin Way
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
Value isnt changing and I cant seem to get the conversion to wor.pdf
Value isnt changing and I cant seem to get the conversion to wor.pdfValue isnt changing and I cant seem to get the conversion to wor.pdf
Value isnt changing and I cant seem to get the conversion to wor.pdf
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
 
google play service 7.8 & new tech in M
google play service 7.8 & new tech in M google play service 7.8 & new tech in M
google play service 7.8 & new tech in M
 
package org dev
package org devpackage org dev
package org dev
 
Package org dev
Package org devPackage org dev
Package org dev
 
Maps
MapsMaps
Maps
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Mastering RecyclerView Layouts

  • 1. Mastering RecyclerView Layouts Dave Smith • NewCircle, Inc. @devunwired +DaveSmithDev
  • 2. Why Am I Here? Help Reduce Sanitarium Admissions caused by RecyclerView Layouts.
  • 3.
  • 4. RecyclerView recyclerView = new RecyclerView(this);
 recyclerView.setLayoutManager(…);
 
 setContentView(recyclerView);
  • 5. LinearLayoutManager LinearLayoutManager manager = new LinearLayoutManager(
 this,
 LinearLayoutManager.VERTICAL,
 false);
  • 6. GridLayoutManager GridLayoutManager manager = new GridLayoutManager( this,
 2, /* Number of grid columns */
 GridLayoutManager.VERTICAL,
 false);
  • 7. GridLayoutManager GridLayoutManager manager = new GridLayoutManager( this,
 2, /* Number of grid columns */
 GridLayoutManager.VERTICAL,
 false); manager.setSpanSizeLookup(
 new GridLayoutManager.SpanSizeLookup() {
 @Override
 public int getSpanSize(int position) {
 //Stagger every other row
 return (position % 3 == 0 ? 2 : 1);
 }
 });
  • 8. StaggeredGridLayoutManager StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(
 2, /* Number of grid columns */
 StaggeredGridLayoutManager.VERTICAL);
  • 9. Case Study: FixedGridLayoutManager 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
  • 16. The Fill Technique fillGaps() Discover first visible position/location Find layout gaps (at the edges) Scrap everything Lay out all visible positions Save as little state as possible. Is there space before the first visible position? Is there space after the last visible position?
  • 17. The Fill Technique private void fillGrid(int direction, …,
 RecyclerView.Recycler recycler,
 RecyclerView.State state) {
 //…Obtain the first visible item position… 
 detachAndScrapAttachedViews(recycler);
 
 for (…) {
 int nextPosition = …;
 
 View View = recycler.getViewForPosition(nextPosition); addView(view);
 
 measureChildWithMargins(view, …);
 layoutDecorated(view, …);
 }
 

  • 18. private void fillGrid(int direction, …,
 RecyclerView.Recycler recycler,
 RecyclerView.State state) {
 //…Obtain the first visible item position… 
 detachAndScrapAttachedViews(recycler);
 
 for (…) {
 int nextPosition = …;
 
 View View = recycler.getViewForPosition(nextPosition); addView(view);
 
 measureChildWithMargins(view, …);
 layoutDecorated(view, …);
 }
 
 //Remove anything that is left behind final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList();
 for (int i=0; i < scrapList.size(); i++) {
 final View removingView = scrapList.get(i);
 recycler.recycleView(removingView);
 }
 }
  • 19. 0 1 2 3 4 5 6 7 Use Attach/ Detach to quickly reorder view indices.
  • 20. Level 1: Make It Work onLayoutChildren() Run a FILL operation canScrollVertically() canScrollHorizontally() Which axes enable scrolling? scrollHorizontallyBy() scrollVerticallyBy() Clamp supplied delta against boundary conditions Shift all views in the layout Trigger a FILL operation Report back actual distance scrolled
  • 21. Level 1: Make It Work public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
 …
 
 int delta;
 if (dx > 0) { // Contents are scrolling left
 delta = …;
 } else { // Contents are scrolling right
 delta = …;
 }
 
 offsetChildrenHorizontal(delta);
 
 if (dx > 0) {
 fillGrid(DIRECTION_START, …, recycler, state);
 } else {
 fillGrid(DIRECTION_END, …, recycler, state);
 }
 
 return -delta;
 }
  • 22. Level 2: Data Set Changes onAdapterChanged() removeAllViews() notifyDataSetChanged() -> onLayoutChanged() Treat as a new layout, and just run a FILL…
  • 23. Level 3: Add Some Flair scrollToPosition() Track Requested Position Trigger requestLayout() smoothScrollToPosition() Create a SmoothScroller instance Set the target position Invoke startSmoothScroll()
  • 24. Level 3: Add Some Flair LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) {
 
 @Override
 public PointF computeScrollVectorForPosition(int targetPosition) {
 final int rowOffset = …;
 final int columnOffset = …;
 
 return new PointF(columnOffset * stepWidth, rowOffset * stepHeight);
 }
 }; 
 scroller.setTargetPosition(position);
 startSmoothScroll(scroller);
  • 25. Level 4: Zen Master supportsPredictiveItemAnimations() We have more to say about animations… onLayoutChildren() [isPreLayout() == true] Note any removed views -> LayoutParams.isViewRemoved() Add extra views during FILL to cover space left behind onLayoutChildren() Place disappearing views off-screen
  • 26. public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
 … 
 if (state.isPreLayout()) {
 final View child = getChildAt(…); final LayoutParams lp = (LayoutParams) child.getLayoutParams();
 if (lp.isItemRemoved()) { //Track and count view removals… }
 }
 
 //Clear all attached views into the recycle bin
 detachAndScrapAttachedViews(recycler);
 
 //Fill the grid for the initial layout of views
 fillGrid(…);
 
 //Anything left? Lay out for disappearing animation
 if (!state.isPreLayout() && !recycler.getScrapList().isEmpty()) {
 final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList();
 //Laying out a scrap item removes it from the list… //Beware concurrent modification! 
 …
 }
 }
  • 29. Resources RecyclerView Playground https://github.com/devunwired/recyclerview-playground Building a RecyclerView LayoutManager http://wiresareobsolete.com/ Redux - Handling Disconnected Ranges Android SDK Reference https://developer.android.com/training/material/lists-cards.html