-
- All Implemented Interfaces:
-
tds.androidx.recyclerview.widget.ItemTouchHelper.ViewDropHandler
,tds.androidx.recyclerview.widget.RecyclerView.SmoothScroller.ScrollVectorProvider
public class GridLayoutManager extends LinearLayoutManager
A RecyclerView.LayoutManager implementations that lays out items in a grid.
By default, each item occupies 1 span. You can change it by providing a custom SpanSizeLookup instance via setSpanSizeLookup.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public abstract class
GridLayoutManager.SpanSizeLookup
A helper class to provide the number of spans each item occupies.
Default implementation sets each item to occupy exactly 1 span.
public final class
GridLayoutManager.DefaultSpanSizeLookup
Default implementation for SpanSizeLookup. Each item occupies 1 span.
public class
GridLayoutManager.LayoutParams
LayoutParams used by GridLayoutManager.
Note that if the orientation is VERTICAL, the width parameter is ignored and if theorientation is HORIZONTAL the height parameter is ignored because child view isexpected to fill all of the space given to it.
-
Field Summary
Fields Modifier and Type Field Description public final static int
DEFAULT_SPAN_COUNT
-
Constructor Summary
Constructors Constructor Description GridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Constructor used when layout manager is set in XML by RecyclerView attribute"layoutManager". GridLayoutManager(Context context, int spanCount)
Creates a vertical GridLayoutManager GridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout)
-
Method Summary
Modifier and Type Method Description void
setStackFromEnd(boolean stackFromEnd)
stackFromEnd is not supported by GridLayoutManager. int
getRowCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state)
Returns the number of rows for accessibility. int
getColumnCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state)
Returns the number of columns for accessibility. void
onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
Lay out all relevant child views from the given adapter.The LayoutManager is in charge of the behavior of item animations. void
onLayoutCompleted(RecyclerView.State state)
Called after a full layout calculation is finished. void
onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount)
Called when items have been added to the adapter. void
onItemsChanged(RecyclerView recyclerView)
Called in response to a call to notifyDataSetChanged or swapAdapter ()} and signals that the the entiredata set has changed. void
onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount)
Called when items have been removed from the adapter. void
onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload)
Called when items have been changed in the adapter and with optional payload. void
onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount)
Called when an item is moved withing the adapter. RecyclerView.LayoutParams
generateDefaultLayoutParams()
Create a default LayoutParams
object for a child of the RecyclerView.RecyclerView.LayoutParams
generateLayoutParams(Context c, AttributeSet attrs)
Create a LayoutParams object suitable for this LayoutManager froman inflated layout resource. RecyclerView.LayoutParams
generateLayoutParams(ViewGroup.LayoutParams lp)
Create a LayoutParams object suitable for this LayoutManager, copying relevantvalues from the supplied LayoutParams object if possible. boolean
checkLayoutParams(RecyclerView.LayoutParams lp)
Determines the validity of the supplied LayoutParams object. void
setSpanSizeLookup(GridLayoutManager.SpanSizeLookup spanSizeLookup)
Sets the source to get the number of spans occupied by each item in the adapter. GridLayoutManager.SpanSizeLookup
getSpanSizeLookup()
Returns the current SpanSizeLookup used by the GridLayoutManager. void
setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec)
Sets the measured dimensions from the given bounding box of the children and themeasurement specs that were passed into onMeasure. int
scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state)
Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.The default implementation does nothing and returns 0. int
scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state)
Scroll vertically by dy pixels in screen coordinates and return the distance traveled.The default implementation does nothing and returns 0. int
getSpanCount()
Returns the number of spans laid out by this grid. void
setSpanCount(int spanCount)
Sets the number of spans to be laid out. View
onFocusSearchFailed(View focused, int focusDirection, RecyclerView.Recycler recycler, RecyclerView.State state)
Called when searching for a focusable view in the given direction has failedfor the current content of the RecyclerView. boolean
supportsPredictiveItemAnimations()
Returns whether this LayoutManager supports "predictive item animations". int
computeHorizontalScrollRange(RecyclerView.State state)
Override this method if you want to support scroll bars. int
computeVerticalScrollRange(RecyclerView.State state)
Override this method if you want to support scroll bars. int
computeHorizontalScrollOffset(RecyclerView.State state)
Override this method if you want to support scroll bars. int
computeVerticalScrollOffset(RecyclerView.State state)
Override this method if you want to support scroll bars. void
setUsingSpansToEstimateScrollbarDimensions(boolean useSpansToEstimateScrollBarDimensions)
When this flag is set, the scroll offset and scroll range calculations will take accountof span information. boolean
isUsingSpansToEstimateScrollbarDimensions()
Returns true if the scroll offset and scroll range calculations take account of spaninformation. -
Methods inherited from class tds.androidx.recyclerview.widget.LinearLayoutManager
assertNotInLayoutOrScroll, canScrollHorizontally, canScrollVertically, collectAdjacentPrefetchPositions, collectInitialPrefetchPositions, computeHorizontalScrollExtent, computeScrollVectorForPosition, computeVerticalScrollExtent, findFirstCompletelyVisibleItemPosition, findFirstVisibleItemPosition, findLastCompletelyVisibleItemPosition, findLastVisibleItemPosition, findViewByPosition, getInitialPrefetchItemCount, getOrientation, getRecycleChildrenOnDetach, getReverseLayout, getStackFromEnd, isAutoMeasureEnabled, isSmoothScrollbarEnabled, onDetachedFromWindow, onInitializeAccessibilityEvent, onRestoreInstanceState, onSaveInstanceState, prepareForDrop, scrollToPosition, scrollToPositionWithOffset, setInitialPrefetchItemCount, setOrientation, setRecycleChildrenOnDetach, setReverseLayout, setSmoothScrollbarEnabled, smoothScrollToPosition
-
Methods inherited from class tds.androidx.recyclerview.widget.RecyclerView.LayoutManager
addDisappearingView, addDisappearingView, addView, addView, assertInLayoutOrScroll, attachView, attachView, attachView, calculateItemDecorationsForChild, checkLayoutParams, chooseSize, collectAdjacentPrefetchPositions, collectInitialPrefetchPositions, computeHorizontalScrollExtent, computeHorizontalScrollOffset, computeHorizontalScrollRange, computeVerticalScrollExtent, computeVerticalScrollOffset, computeVerticalScrollRange, detachAndScrapAttachedViews, detachAndScrapView, detachAndScrapViewAt, detachView, detachViewAt, endAnimation, findContainingItemView, getBaseline, getBottomDecorationHeight, getChildAt, getChildCount, getChildMeasureSpec, getChildMeasureSpec, getClipToPadding, getColumnCountForAccessibility, getDecoratedBottom, getDecoratedBoundsWithMargins, getDecoratedLeft, getDecoratedMeasuredHeight, getDecoratedMeasuredWidth, getDecoratedRight, getDecoratedTop, getFocusedChild, getHeight, getHeightMode, getItemCount, getItemViewType, getLayoutDirection, getLeftDecorationWidth, getMinimumHeight, getMinimumWidth, getPaddingBottom, getPaddingEnd, getPaddingLeft, getPaddingRight, getPaddingStart, getPaddingTop, getPosition, getProperties, getRightDecorationWidth, getRowCountForAccessibility, getTopDecorationHeight, getTransformedBoundingBox, getWidth, getWidthMode, hasFocus, ignoreView, isAttachedToWindow, isFocused, isItemPrefetchEnabled, isLayoutHierarchical, isMeasurementCacheEnabled, isSmoothScrolling, isViewPartiallyVisible, layoutDecorated, layoutDecoratedWithMargins, measureChild, measureChildWithMargins, moveView, offsetChildrenHorizontal, offsetChildrenVertical, onAdapterChanged, onAddFocusables, onAttachedToWindow, onDetachedFromWindow, onDetachedFromWindow, onFocusSearchFailed, onInitializeAccessibilityEvent, onInitializeAccessibilityEvent, onInterceptFocusSearch, onItemsAdded, onItemsChanged, onItemsMoved, onItemsRemoved, onItemsUpdated, onItemsUpdated, onLayoutChildren, onLayoutCompleted, onMeasure, onRequestChildFocus, onRequestChildFocus, onScrollStateChanged, postOnAnimation, removeAllViews, removeAndRecycleAllViews, removeAndRecycleView, removeAndRecycleViewAt, removeCallbacks, removeDetachedView, removeView, removeViewAt, requestChildRectangleOnScreen, requestChildRectangleOnScreen, requestLayout, requestSimpleAnimationsInNextLayout, scrollHorizontallyBy, scrollVerticallyBy, setAutoMeasureEnabled, setItemPrefetchEnabled, setMeasuredDimension, setMeasurementCacheEnabled, smoothScrollToPosition, startSmoothScroll, stopIgnoringView
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Constructor Detail
-
GridLayoutManager
GridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Constructor used when layout manager is set in XML by RecyclerView attribute"layoutManager".
-
GridLayoutManager
GridLayoutManager(Context context, int spanCount)
Creates a vertical GridLayoutManager- Parameters:
context
- Current context, will be used to access resources.spanCount
- The number of columns in the grid
-
GridLayoutManager
GridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout)
- Parameters:
context
- Current context, will be used to access resources.spanCount
- The number of columns or rows in the gridorientation
- Layout orientation.reverseLayout
- When set to true, layouts from end to start.
-
-
Method Detail
-
setStackFromEnd
void setStackFromEnd(boolean stackFromEnd)
stackFromEnd is not supported by GridLayoutManager. Consider using setReverseLayout.
-
getRowCountForAccessibility
int getRowCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state)
Returns the number of rows for accessibility.
Default implementation returns the number of items in the adapter if LayoutManagersupports vertical scrolling or 1 if LayoutManager does not support verticalscrolling.
- Parameters:
recycler
- The Recycler that can be used to convert view positions into adapterpositionsstate
- The current state of RecyclerView
-
getColumnCountForAccessibility
int getColumnCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state)
Returns the number of columns for accessibility.
Default implementation returns the number of items in the adapter if LayoutManagersupports horizontal scrolling or 1 if LayoutManager does not support horizontalscrolling.
- Parameters:
recycler
- The Recycler that can be used to convert view positions into adapterpositionsstate
- The current state of RecyclerView
-
onLayoutChildren
void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
Lay out all relevant child views from the given adapter.The LayoutManager is in charge of the behavior of item animations. By default,RecyclerView has a non-null #getItemAnimator() ItemAnimator, and simpleitem animations are enabled. This means that add/remove operations on theadapter will result in animations to add new or appearing items, removed ordisappearing items, and moved items. If a LayoutManager returns false from #supportsPredictiveItemAnimations(), which is the default, and runs anormal layout operation during #onLayoutChildren(Recycler, State), theRecyclerView will have enough information to run those animations in a simpleway. For example, the default ItemAnimator, , willsimply fade views in and out, whether they are actually added/removed or whetherthey are moved on or off the screen due to other add/remove operations.
A LayoutManager wanting a better item animation experience, where items can beanimated onto and off of the screen according to where the items exist when theyare not on screen, then the LayoutManager should return true from #supportsPredictiveItemAnimations() and add additional logic to #onLayoutChildren(Recycler, State). Supporting predictive animationsmeans that #onLayoutChildren(Recycler, State) will be called twice;once as a "pre" layout step to determine where items would have been prior toa real layout, and again to do the "real" layout. In the pre-layout phase,items will remember their pre-layout positions to allow them to be laid outappropriately. Also, LayoutParams#isItemRemoved() removed items willbe returned from the scrap to help determine correct placement of other items.These removed items should not be added to the child list, but should be usedto help calculate correct positioning of other views, including views thatwere not previously onscreen (referred to as APPEARING views), but whosepre-layout offscreen position can be determined given the extrainformation about the pre-layout removed views.
The second layout pass is the real layout in which only non-removed viewswill be used. The only additional requirement during this pass is, if #supportsPredictiveItemAnimations() returns true, to note whichviews exist in the child list prior to layout and which are not there afterlayout (referred to as DISAPPEARING views), and to position/layout those viewsappropriately, without regard to the actual bounds of the RecyclerView. This allowsthe animation system to know the location to which to animate these disappearingviews.
The default LayoutManager implementations for RecyclerView handle all of theserequirements for animations already. Clients of RecyclerView can either use oneof these layout managers directly or look at their implementations ofonLayoutChildren() to see how they account for the APPEARING andDISAPPEARING views.
-
onLayoutCompleted
void onLayoutCompleted(RecyclerView.State state)
Called after a full layout calculation is finished. The layout calculation may includemultiple onLayoutChildren calls due to animations orlayout measurement but it will include only one onLayoutCompleted call.This method will be called at the end of layout call.
This is a good place for the LayoutManager to do some cleanup like pending scrollposition, saved state etc.
- Parameters:
state
- Transient state of RecyclerView
-
onItemsAdded
void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount)
Called when items have been added to the adapter. The LayoutManager may choose torequestLayout if the inserted items would require refreshing the currently visible setof child views. (e.g. currently empty space would be filled by appended items, etc.)
-
onItemsChanged
void onItemsChanged(RecyclerView recyclerView)
Called in response to a call to notifyDataSetChanged or swapAdapter ()} and signals that the the entiredata set has changed.
-
onItemsRemoved
void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount)
Called when items have been removed from the adapter.
-
onItemsUpdated
void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload)
Called when items have been changed in the adapter and with optional payload.Default implementation calls onItemsUpdated.
-
onItemsMoved
void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount)
Called when an item is moved withing the adapter.
Note that, an item may also change position in response to another ADD/REMOVE/MOVEoperation. This callback is only called if and only if notifyItemMoved is called.
-
generateDefaultLayoutParams
RecyclerView.LayoutParams generateDefaultLayoutParams()
Create a default
LayoutParams
object for a child of the RecyclerView.LayoutManagers will often want to use a custom
LayoutParams
typeto store extra information specific to the layout. Client code should subclass for this purpose.Important: if you use your own custom
LayoutParams
typeyou must also override #checkLayoutParams(LayoutParams), #generateLayoutParams(ViewGroup.LayoutParams) and #generateLayoutParams(Context, AttributeSet).
-
generateLayoutParams
RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs)
Create a LayoutParams object suitable for this LayoutManager froman inflated layout resource.
Important: if you use your own custom
LayoutParams
typeyou must also override checkLayoutParams, generateLayoutParams and generateLayoutParams.- Parameters:
c
- Context for obtaining styled attributesattrs
- AttributeSet describing the supplied arguments
-
generateLayoutParams
RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp)
Create a LayoutParams object suitable for this LayoutManager, copying relevantvalues from the supplied LayoutParams object if possible.
Important: if you use your own custom
LayoutParams
typeyou must also override checkLayoutParams, generateLayoutParams and generateLayoutParams.- Parameters:
lp
- Source LayoutParams object to copy values from
-
checkLayoutParams
boolean checkLayoutParams(RecyclerView.LayoutParams lp)
Determines the validity of the supplied LayoutParams object.
This should check to make sure that the object is of the correct typeand all values are within acceptable ranges. The default implementationreturns
true
for non-null params.- Parameters:
lp
- LayoutParams object to check
-
setSpanSizeLookup
void setSpanSizeLookup(GridLayoutManager.SpanSizeLookup spanSizeLookup)
Sets the source to get the number of spans occupied by each item in the adapter.
- Parameters:
spanSizeLookup
- SpanSizeLookup instance to be used to query number of spansoccupied by each item
-
getSpanSizeLookup
GridLayoutManager.SpanSizeLookup getSpanSizeLookup()
Returns the current SpanSizeLookup used by the GridLayoutManager.
-
setMeasuredDimension
void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec)
Sets the measured dimensions from the given bounding box of the children and themeasurement specs that were passed into onMeasure. It isonly called if a LayoutManager returns
true
from isAutoMeasureEnabled and it is called after the RecyclerView calls onLayoutChildren in the execution of onMeasure.This method must call setMeasuredDimension.
The default implementation adds the RecyclerView's padding to the given bounding boxthen caps the value to be within the given measurement specs.
- Parameters:
childrenBounds
- The bounding box of all childrenwSpec
- The widthMeasureSpec that was passed into the RecyclerView.hSpec
- The heightMeasureSpec that was passed into the RecyclerView.
-
scrollHorizontallyBy
int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state)
Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.The default implementation does nothing and returns 0.
-
scrollVerticallyBy
int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state)
Scroll vertically by dy pixels in screen coordinates and return the distance traveled.The default implementation does nothing and returns 0.
-
getSpanCount
int getSpanCount()
Returns the number of spans laid out by this grid.
-
setSpanCount
void setSpanCount(int spanCount)
Sets the number of spans to be laid out.
If getOrientation is VERTICAL, this is the number of columns.If getOrientation is HORIZONTAL, this is the number of rows.
- Parameters:
spanCount
- The total number of spans in the grid
-
onFocusSearchFailed
View onFocusSearchFailed(View focused, int focusDirection, RecyclerView.Recycler recycler, RecyclerView.State state)
Called when searching for a focusable view in the given direction has failedfor the current content of the RecyclerView.
This is the LayoutManager's opportunity to populate views in the given directionto fulfill the request if it can. The LayoutManager should attach and returnthe view to be focused, if a focusable view in the given direction is found.Otherwise, if all the existing (or the newly populated views) are unfocusable, it returnsthe next unfocusable view to become visible on the screen. This unfocusable view istypically the first view that's either partially or fully out of RV's padded boundedarea in the given direction. The default implementation returns null.
- Parameters:
focused
- The currently focused viewrecycler
- The recycler to use for obtaining views for currently offscreen itemsstate
- Transient state of RecyclerView
-
supportsPredictiveItemAnimations
boolean supportsPredictiveItemAnimations()
Returns whether this LayoutManager supports "predictive item animations".
"Predictive item animations" are automatically created animations that showwhere items came from, and where they are going to, as items are added, removed,or moved within a layout.
A LayoutManager wishing to support predictive item animations must override thismethod to return true (the default implementation returns false) and must obey certainbehavioral contracts outlined in onLayoutChildren.
Whether item animations actually occur in a RecyclerView is actually determined by boththe return value from this method and the ItemAnimator set on theRecyclerView itself. If the RecyclerView has a non-null ItemAnimator but thismethod returns false, then only "simple item animations" will be enabled in theRecyclerView, in which views whose position are changing are simply faded in/out. If theRecyclerView has a non-null ItemAnimator and this method returns true, then predictiveitem animations will be enabled in the RecyclerView.
-
computeHorizontalScrollRange
int computeHorizontalScrollRange(RecyclerView.State state)
Override this method if you want to support scroll bars.
Read computeHorizontalScrollRange for details.
Default implementation returns 0.
- Parameters:
state
- Current State of RecyclerView where you can find total item count
-
computeVerticalScrollRange
int computeVerticalScrollRange(RecyclerView.State state)
Override this method if you want to support scroll bars.
Read computeVerticalScrollRange for details.
Default implementation returns 0.
- Parameters:
state
- Current State of RecyclerView where you can find total item count
-
computeHorizontalScrollOffset
int computeHorizontalScrollOffset(RecyclerView.State state)
Override this method if you want to support scroll bars.
Read computeHorizontalScrollOffset for details.
Default implementation returns 0.
- Parameters:
state
- Current State of RecyclerView where you can find total item count
-
computeVerticalScrollOffset
int computeVerticalScrollOffset(RecyclerView.State state)
Override this method if you want to support scroll bars.
Read computeVerticalScrollOffset for details.
Default implementation returns 0.
- Parameters:
state
- Current State of RecyclerView where you can find total item count
-
setUsingSpansToEstimateScrollbarDimensions
void setUsingSpansToEstimateScrollbarDimensions(boolean useSpansToEstimateScrollBarDimensions)
When this flag is set, the scroll offset and scroll range calculations will take accountof span information.
This is will increase the accuracy of the scroll bar's size and offset but will requiremore calls to getSpanGroupIndex".
This additional accuracy may or may not be needed, depending on the characteristics ofyour layout. You will likely benefit from this accuracy when:
- The variation in item span sizes is large.
- The size of your data set is small (if your data set is large, the scrollbar willlikely be very small anyway, and thus the increased accuracy has less impact).
- Calls to getSpanGroupIndex are fast.
If you decide to enable this feature, you should be sure that calls to getSpanGroupIndex are fast, that set span group indexcaching is set to true via a call to and span index caching is also enabled via a call to { }.
-
isUsingSpansToEstimateScrollbarDimensions
boolean isUsingSpansToEstimateScrollbarDimensions()
Returns true if the scroll offset and scroll range calculations take account of spaninformation. See setUsingSpansToEstimateScrollbarDimensions for moreinformation on this topic. Defaults to
{@code false}
.
-
-
-
-