Package 

Class StaggeredGridLayoutManager

  • All Implemented Interfaces:
    tds.androidx.recyclerview.widget.RecyclerView.SmoothScroller.ScrollVectorProvider

    
    public class StaggeredGridLayoutManager
    extends RecyclerView.LayoutManager implements RecyclerView.SmoothScroller.ScrollVectorProvider
                        

    A LayoutManager that lays out children in a staggered grid formation. It supports horizontal & vertical layout as well as an ability to layout children in reverse.

    Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, StaggeredGridLayoutManager can offset spans independently or move items between spans. You can control this behavior via setGapStrategy.

    • Constructor Detail

      • StaggeredGridLayoutManager

        StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
        Constructor used when layout manager is set in XML by RecyclerView attribute"layoutManager".
      • StaggeredGridLayoutManager

        StaggeredGridLayoutManager(int spanCount, int orientation)
        Creates a StaggeredGridLayoutManager with given parameters.
        Parameters:
        spanCount - If orientation is vertical, spanCount is number of columns.
        orientation - VERTICAL or HORIZONTAL
    • Method Detail

      • isAutoMeasureEnabled

         boolean isAutoMeasureEnabled()

        Returns whether the measuring pass of layout should use the AutoMeasure mechanism of RecyclerView or if it should be done by the LayoutManager's implementation of onMeasure.

        This method returns false by default (it actually returns the value passed to thedeprecated setAutoMeasureEnabled) and should be overridden to returntrue if a LayoutManager wants to be auto measured by the RecyclerView.

        If this method is overridden to return true, onMeasure should not be overridden.

        AutoMeasure is a RecyclerView mechanism that handles the measuring pass of layout in asimple and contract satisfying way, including the wrapping of children laid out byLayoutManager. Simply put, it handles wrapping children by calling onLayoutChildren during a call to onMeasure, and then calculating desired dimensions basedon children's dimensions and positions. It does this while supporting all existinganimation capabilities of the RecyclerView.

        More specifically:

        • When onMeasure is called, if the provided measurespecs both have a mode of EXACTLY, RecyclerView will set itsmeasured dimensions accordingly and return, allowing layout to continue as normal(Actually, RecyclerView will call onMeasure for backwards compatibilityreasons but it should not be overridden if AutoMeasure is being used).
        • If one of the layout specs is not {@code EXACT}, the RecyclerView will start thelayout process. It will first process all pending Adapter updates andthen decide whether to run a predictive layout. If it decides to do so, it will firstcall onLayoutChildren with isPreLayout set to {@code true}. At this stage, getWidth and getHeight will stillreturn the width and height of the RecyclerView as of the last layout calculation.

          After handling the predictive case, RecyclerView will call onLayoutChildren with isMeasuring set to {@code true} and isPreLayout set to {@code false}. The LayoutManager canaccess the measurement specs via getHeight, getHeightMode, getWidth and getWidthMode.

        • After the layout calculation, RecyclerView sets the measured width & height bycalculating the bounding box for the children (+ RecyclerView's padding). TheLayoutManagers can override setMeasuredDimension to choosedifferent values. For instance, GridLayoutManager overrides this value to handle the casewhere if it is vertical and has 3 columns but only 2 items, it should still measure itswidth to fit 3 items, not 2.
        • Any following calls to onMeasure will run onLayoutChildren with isMeasuring set to {@code true} and isPreLayout set to {@code false}. RecyclerView willtake care of which views are actually added / removed / moved / changed for animations sothat the LayoutManager should not worry about them and handle each onLayoutChildren call as if it is the last one.
        • When measure is complete and RecyclerView's onLayout method is called, RecyclerView checkswhether it already did layout calculations during the measure pass and if so, it re-usesthat information. It may still decide to call onLayoutChildren if the last measure spec was different from the final dimensions or adapter contentshave changed between the measure call and the layout call.
        • Finally, animations are calculated and run as usual.
      • onScrollStateChanged

         void onScrollStateChanged(int state)

        RecyclerView calls this method to notify LayoutManager that scroll state has changed.

        Parameters:
        state - The new scroll state for RecyclerView
      • onDetachedFromWindow

         void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler)

        Called when this LayoutManager is detached from its parent RecyclerView or whenits parent RecyclerView is detached from its window.

        LayoutManager should clear all of its View references as another LayoutManager might beassigned to the RecyclerView.

        If the RecyclerView is re-attached with the same LayoutManager and Adapter, it may notcall onLayoutChildren if nothing has changed and a layout wasnot requested on the RecyclerView while it was detached.

        If your LayoutManager has View references that it cleans in on-detach, it should alsocall requestLayout to ensure that it is re-laid out whenRecyclerView is re-attached.

        Subclass implementations should always call through to the superclass implementation.

        Parameters:
        view - The RecyclerView this LayoutManager is bound to
        recycler - The recycler to use if you prefer to recycle your children instead ofkeeping them around.
      • setSpanCount

         void setSpanCount(int spanCount)

        Sets the number of spans for the layout. This will invalidate all of the span assignmentsfor Views.

        Calling this method will automatically result in a new layout request unless the spanCountparameter is equal to current span count.

        Parameters:
        spanCount - Number of spans to layout
      • setOrientation

         void setOrientation(int orientation)

        Sets the orientation of the layout. StaggeredGridLayoutManager will do its best to keepscroll position if this method is called after views are laid out.

        Parameters:
        orientation - HORIZONTAL or VERTICAL
      • setReverseLayout

         void setReverseLayout(boolean reverseLayout)

        Sets whether LayoutManager should start laying out items from the end of the UI. The orderitems are traversed is not affected by this call.

        For vertical layout, if it is set to true, first item will be at the bottom ofthe list.

        For horizontal layouts, it depends on the layout direction.When set to true, If RecyclerView is LTR, than it will layout from RTL, if RecyclerView} is RTL, it will layout from LTR.

        Parameters:
        reverseLayout - Whether layout should be in reverse or not
      • setGapStrategy

         void setGapStrategy(int gapStrategy)

        Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameteris different than the current strategy, calling this method will trigger a layout request.

        Parameters:
        gapStrategy - The new gap handling strategy.
      • getSpanCount

         int getSpanCount()

        Returns the number of spans laid out by StaggeredGridLayoutManager.

      • invalidateSpanAssignments

         void invalidateSpanAssignments()

        For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items.

        If you need to cancel current assignments, you can call this method which will clear allassignments and request a new layout.

      • getReverseLayout

         boolean getReverseLayout()

        Returns whether views are laid out in reverse order or not.

        Not that this value is not affected by RecyclerView's layout direction.

      • 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 children
        wSpec - The widthMeasureSpec that was passed into the RecyclerView.
        hSpec - The heightMeasureSpec that was passed into the 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 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, theRecyclerView will have enough information to run those animations in a simpleway. For example, the default ItemAnimator, DefaultItemAnimator, 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. Supporting predictive animationsmeans that onLayoutChildren 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, 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.

        Parameters:
        recycler - Recycler to use for fetching potentially cached views for aposition
        state - Transient state of RecyclerView
      • onAdapterChanged

         void onAdapterChanged(@Nullable() RecyclerView.Adapter oldAdapter, @Nullable() RecyclerView.Adapter newAdapter)

        Called if the RecyclerView this LayoutManager is bound to has a different adapter set via setAdapter or swapAdapter. The LayoutManager may use thisopportunity to clear caches and configure state such that it can relayout appropriatelywith the new data and potentially new view types.

        The default implementation removes all currently attached views.

        Parameters:
        oldAdapter - The previous adapter instance.
        newAdapter - The new adapter instance.
      • 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
      • 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.

      • findFirstVisibleItemPositions

         Array<int> findFirstVisibleItemPositions(Array<int> into)

        Returns the adapter position of the first visible view for each span.

        Note that, this value is not affected by layout orientation or item order traversal.(setReverseLayout). Views are sorted by their positions in the adapter,not in the layout.

        If RecyclerView has item decorators, they will be considered in calculations as well.

        StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Thoseviews are ignored in this method.

        Parameters:
        into - An array to put the results into.
      • findFirstCompletelyVisibleItemPositions

         Array<int> findFirstCompletelyVisibleItemPositions(Array<int> into)

        Returns the adapter position of the first completely visible view for each span.

        Note that, this value is not affected by layout orientation or item order traversal.(setReverseLayout). Views are sorted by their positions in the adapter,not in the layout.

        If RecyclerView has item decorators, they will be considered in calculations as well.

        StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Thoseviews are ignored in this method.

        Parameters:
        into - An array to put the results into.
      • findLastVisibleItemPositions

         Array<int> findLastVisibleItemPositions(Array<int> into)

        Returns the adapter position of the last visible view for each span.

        Note that, this value is not affected by layout orientation or item order traversal.(setReverseLayout). Views are sorted by their positions in the adapter,not in the layout.

        If RecyclerView has item decorators, they will be considered in calculations as well.

        StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Thoseviews are ignored in this method.

        Parameters:
        into - An array to put the results into.
      • findLastCompletelyVisibleItemPositions

         Array<int> findLastCompletelyVisibleItemPositions(Array<int> into)

        Returns the adapter position of the last completely visible view for each span.

        Note that, this value is not affected by layout orientation or item order traversal.(setReverseLayout). Views are sorted by their positions in the adapter,not in the layout.

        If RecyclerView has item decorators, they will be considered in calculations as well.

        StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Thoseviews are ignored in this method.

        Parameters:
        into - An array to put the results into.
      • onRestoreInstanceState

         void onRestoreInstanceState(Parcelable state)

        Called when the RecyclerView is ready to restore the state based on a previousRecyclerView.Notice that this might happen after an actual layout, based on how Adapter prefers torestore State. See getStateRestorationPolicy for more information.

        Parameters:
        state - The parcelable that was returned by the previous LayoutManager'sonSaveInstanceState method.
      • onSaveInstanceState

         Parcelable onSaveInstanceState()

        Called when the LayoutManager should save its state. This is a good time to save yourscroll position, configuration and anything else that may be required to restore the samelayout state if the LayoutManager is recreated.

        RecyclerView does NOT verify if the LayoutManager has changed between state save andrestore. This will let you share information between your LayoutManagers but it is alsoyour responsibility to make sure they use the same parcelable class.

      • offsetChildrenHorizontal

         void offsetChildrenHorizontal(int dx)

        Offset all child views attached to the parent RecyclerView by dx pixels alongthe horizontal axis.

        Parameters:
        dx - Pixels to offset by
      • offsetChildrenVertical

         void offsetChildrenVertical(int dy)

        Offset all child views attached to the parent RecyclerView by dy pixels alongthe vertical axis.

        Parameters:
        dy - Pixels to offset by
      • onItemsRemoved

         void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount)

        Called when items have been removed from the adapter.

      • 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.)

      • 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.

      • 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.

      • canScrollVertically

         boolean canScrollVertically()

        Query if vertical scrolling is currently supported. The default implementationreturns false.

      • canScrollHorizontally

         boolean canScrollHorizontally()

        Query if horizontal scrolling is currently supported. The default implementationreturns false.

      • 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.

        Parameters:
        dx - distance to scroll by in pixels.
        recycler - Recycler to use for fetching potentially cached views for aposition
        state - Transient state of RecyclerView
      • 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.

        Parameters:
        dy - distance to scroll in pixels.
        recycler - Recycler to use for fetching potentially cached views for aposition
        state - Transient state of RecyclerView
      • computeScrollVectorForPosition

         PointF computeScrollVectorForPosition(int targetPosition)

        Should calculate the vector that points to the direction where the target positioncan be found.

        This method is used by the LinearSmoothScroller to initiate a scroll towardsthe target position.

        The magnitude of the vector is not important. It is always normalized before beingused by the LinearSmoothScroller.

        LayoutManager should not check whether the position exists in the adapter or not.

        Parameters:
        targetPosition - the target position to which the returned vector should point
      • smoothScrollToPosition

         void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position)

        Smooth scroll to the specified adapter position.

        To support smooth scrolling, override this method, create your SmoothScroller instance and call startSmoothScroll.

        Parameters:
        recyclerView - The RecyclerView to which this layout manager is attached
        state - Current State of RecyclerView
        position - Scroll to this adapter position.
      • scrollToPosition

         void scrollToPosition(int position)

        Scroll to the specified adapter position.Actual position of the item on the screen depends on the LayoutManager implementation.

        Parameters:
        position - Scroll to this adapter position.
      • scrollToPositionWithOffset

         void scrollToPositionWithOffset(int position, int offset)

        Scroll to the specified adapter position with the given offset from layout start.

        Note that scroll position change will not be reflected until the next layout call.

        If you are just trying to make a position visible, use scrollToPosition.

        Parameters:
        position - Index (starting at 0) of the reference item.
        offset - The distance (in pixels) between the start edge of the item view andstart edge of the RecyclerView.
      • 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
      • onFocusSearchFailed

        @Nullable() View onFocusSearchFailed(View focused, int direction, 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 view
        direction - One of FOCUS_UP, FOCUS_DOWN,FOCUS_LEFT, FOCUS_RIGHT,FOCUS_BACKWARD, FOCUS_FORWARD or 0 for not applicable
        recycler - The recycler to use for obtaining views for currently offscreen items
        state - Transient state of RecyclerView