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

Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room LibraryReinvently
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplateGuo Albert
 
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...Severalnines
 
MySQL InnoDB Cluster HA Overview & Demo
MySQL InnoDB Cluster HA Overview & DemoMySQL InnoDB Cluster HA Overview & Demo
MySQL InnoDB Cluster HA Overview & DemoKeith Hollman
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Sqlite
SqliteSqlite
SqliteKumar
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 

What's hot (20)

SOLID principles
SOLID principlesSOLID principles
SOLID principles
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Sqlite
SqliteSqlite
Sqlite
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...
MySQL Load Balancers - Maxscale, ProxySQL, HAProxy, MySQL Router & nginx - A ...
 
MySQL InnoDB Cluster HA Overview & Demo
MySQL InnoDB Cluster HA Overview & DemoMySQL InnoDB Cluster HA Overview & Demo
MySQL InnoDB Cluster HA Overview & Demo
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Sqlite
SqliteSqlite
Sqlite
 
Jdbc
Jdbc   Jdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
Jboss Tutorial Basics
Jboss Tutorial BasicsJboss Tutorial Basics
Jboss Tutorial Basics
 
Towards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal ArchitectureTowards Functional Programming through Hexagonal Architecture
Towards Functional Programming through Hexagonal Architecture
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 

Viewers also liked

Build and Distributing SDK Add-Ons
Build and Distributing SDK Add-OnsBuild and Distributing SDK Add-Ons
Build and Distributing SDK Add-OnsDave Smith
 
Master of RecyclerView
Master of RecyclerViewMaster of RecyclerView
Master of RecyclerViewYuki Anzai
 
ExtraLayoutSpace of RecyclerView
ExtraLayoutSpace of RecyclerViewExtraLayoutSpace of RecyclerView
ExtraLayoutSpace of RecyclerViewMima Yuki
 
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 tipsNexus FrontierTech
 
The Tale of a Smooth RecyclerView
The Tale of a Smooth RecyclerViewThe Tale of a Smooth RecyclerView
The Tale of a Smooth RecyclerViewSimek Adam
 
More Android UIs
More Android UIsMore Android UIs
More Android UIsDENNIS JUNG
 
Infinum Android Talks #09 - UI optimization
Infinum Android Talks #09 - UI optimization Infinum Android Talks #09 - UI optimization
Infinum Android Talks #09 - UI optimization Infinum
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesMarakana Inc.
 
Food Waste Recycling Education - Obeo
Food Waste Recycling Education - ObeoFood Waste Recycling Education - Obeo
Food Waste Recycling Education - ObeoObeo Ltd.
 
Zero waste action plan 2010
Zero waste action plan 2010Zero waste action plan 2010
Zero waste action plan 2010walled ashwah
 
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 MVVMAdil Mughal
 
Android 02 - Recycler View Adapter
Android 02 - Recycler View AdapterAndroid 02 - Recycler View Adapter
Android 02 - Recycler View AdapterAline Borges
 
Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Khaled Anaqwa
 
Tutorial android - créer des apps
Tutorial android - créer des appsTutorial android - créer des apps
Tutorial android - créer des appsNoé Breiss
 
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 Part2Mathias Seguy
 
droidgirls Recyclerview
droidgirls Recyclerviewdroidgirls Recyclerview
droidgirls RecyclerviewYuki Anzai
 

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

Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewDeep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewTakeshi Hagikura
 
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 | ReduxCodifly
 
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksBeginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeks
Beginning direct3d gameprogramming06_firststepstoanimation_20161115_jintaeksJinTaek Seo
 
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 XamarinXamarin
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018Tracy Lee
 
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 NinjaDroidConTLV
 
Prescribing RX Responsibly
Prescribing RX ResponsiblyPrescribing RX Responsibly
Prescribing RX ResponsiblyNareg Khoshafian
 
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 lCodecamp Romania
 
MVI - Managing State The Kotlin Way
MVI - Managing State The Kotlin WayMVI - Managing State The Kotlin Way
MVI - Managing State The Kotlin WayZeyad Gasser
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
 
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.pdfamirthagiftsmadurai
 
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.Astrails
 
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 Ted Liang
 

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

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 

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