LinearLayoutManager

open class LinearLayoutManager : RecyclerView.LayoutManager, ItemTouchHelper.ViewDropHandler, RecyclerView.SmoothScroller.ScrollVectorProvider
kotlin.Any
   ↳ androidx.recyclerview.widget.RecyclerView.LayoutManager
   ↳ androidx.recyclerview.widget.LinearLayoutManager

A RecyclerView.LayoutManager implementation which provides similar functionality to android.widget.ListView.

Summary

Nested classes

open

Constants

static Int

static Int

static Int

Public constructors

<init>(context: Context!)

Creates a vertical LinearLayoutManager

<init>(context: Context!, orientation: Int, reverseLayout: Boolean)

<init>(context: Context!, attrs: AttributeSet!, defStyleAttr: Int, defStyleRes: Int)

Constructor used when layout manager is set in XML by RecyclerView attribute "layoutManager".

Public methods

open Unit

open Boolean

open Boolean

open Unit

open Unit

open Int

open Int

open Int

open PointF?

open Int

open Int

open Int

open Int

Returns the adapter position of the first fully visible view.

open Int

Returns the adapter position of the first visible view.

open Int

Returns the adapter position of the last fully visible view.

open Int

Returns the adapter position of the last visible view.

open View?

Finds the view which represents the given adapter position.

open RecyclerView.LayoutParams!

Create a default LayoutParams object for a child of the RecyclerView.

open Int

Gets the number of items to prefetch in collectInitialPrefetchPositions(int, LayoutPrefetchRegistry), which defines how many inner items should be prefetched when this LayoutManager's RecyclerView is nested inside another RecyclerView.

open Int

Returns the current orientation of the layout.

open Boolean

Returns whether LayoutManager will recycle its children when it is detached from RecyclerView.

open Boolean

Returns if views are laid out from the opposite direction of the layout.

open Boolean

open Boolean

open Boolean

Returns the current state of the smooth scrollbar feature.

open Unit

open View?
onFocusSearchFailed(focused: View, focusDirection: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State)

open Unit

open Unit

Lay out all relevant child views from the given adapter.

open Unit

open Unit

open Parcelable?

open Unit
prepareForDrop(@NonNull view: View, @NonNull target: View, x: Int, y: Int)

Called by the ItemTouchHelper after a View is dropped over another View.

open Int

Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.

open Unit
scrollToPosition(position: Int)

Scroll the RecyclerView to make the position visible.

open Unit
scrollToPositionWithOffset(position: Int, offset: Int)

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

open Int

Scroll vertically by dy pixels in screen coordinates and return the distance traveled.

open Unit

Sets the number of items to prefetch in collectInitialPrefetchPositions(int, LayoutPrefetchRegistry), which defines how many inner items should be prefetched when this LayoutManager's RecyclerView is nested inside another RecyclerView.

open Unit
setOrientation(orientation: Int)

Sets the orientation of the layout.

open Unit
setRecycleChildrenOnDetach(recycleChildrenOnDetach: Boolean)

Set whether LayoutManager will recycle its children when it is detached from RecyclerView.

open Unit
setReverseLayout(reverseLayout: Boolean)

Used to reverse item traversal and layout order.

open Unit

When smooth scrollbar is enabled, the position and size of the scrollbar thumb is computed based on the number of visible pixels in the visible items.

open Unit
setStackFromEnd(stackFromEnd: Boolean)

Compatibility support for android.widget.AbsListView#setStackFromBottom(boolean)

open Unit
smoothScrollToPosition(recyclerView: RecyclerView!, state: RecyclerView.State!, position: Int)

open Boolean

Protected methods

open Unit
calculateExtraLayoutSpace(@NonNull state: RecyclerView.State, @NonNull extraLayoutSpace: IntArray)

Calculates the amount of extra space (in pixels) that should be laid out by and stores the result in extraLayoutSpace.

open Int

Returns the amount of extra space that should be laid out by LayoutManager.

open Boolean

Inherited functions

Constants

HORIZONTAL

static val HORIZONTAL: Int
Value: RecyclerView.HORIZONTAL

INVALID_OFFSET

static val INVALID_OFFSET: Int
Value: Integer.MIN_VALUE

VERTICAL

static val VERTICAL: Int
Value: RecyclerView.VERTICAL

Public constructors

<init>

LinearLayoutManager(context: Context!)

Creates a vertical LinearLayoutManager

Parameters
context Context!: Current context, will be used to access resources.

<init>

LinearLayoutManager(context: Context!, orientation: Int, reverseLayout: Boolean)
Parameters
context Context!: Current context, will be used to access resources.
orientation Context!: Layout orientation. Should be HORIZONTAL or .
reverseLayout Context!: When set to true, layouts from end to start.

<init>

LinearLayoutManager(context: Context!, attrs: AttributeSet!, defStyleAttr: Int, defStyleRes: Int)

Constructor used when layout manager is set in XML by RecyclerView attribute "layoutManager". Defaults to vertical orientation. android.R.attr#orientation androidx.recyclerview.R.attr#reverseLayout androidx.recyclerview.R.attr#stackFromEnd

Public methods

assertNotInLayoutOrScroll

open fun assertNotInLayoutOrScroll(message: String!): Unit

canScrollHorizontally

open fun canScrollHorizontally(): Boolean
Return
Boolean: true if getOrientation() is HORIZONTAL

canScrollVertically

open fun canScrollVertically(): Boolean
Return
Boolean: true if getOrientation() is VERTICAL

collectAdjacentPrefetchPositions

open fun collectAdjacentPrefetchPositions(dx: Int, dy: Int, state: RecyclerView.State!, layoutPrefetchRegistry: RecyclerView.LayoutManager.LayoutPrefetchRegistry!): Unit

collectInitialPrefetchPositions

open fun collectInitialPrefetchPositions(adapterItemCount: Int, layoutPrefetchRegistry: RecyclerView.LayoutManager.LayoutPrefetchRegistry!): Unit

computeHorizontalScrollExtent

open fun computeHorizontalScrollExtent(state: RecyclerView.State): Int

computeHorizontalScrollOffset

open fun computeHorizontalScrollOffset(state: RecyclerView.State): Int

computeHorizontalScrollRange

open fun computeHorizontalScrollRange(state: RecyclerView.State): Int

computeScrollVectorForPosition

open fun computeScrollVectorForPosition(targetPosition: Int): PointF?

computeVerticalScrollExtent

open fun computeVerticalScrollExtent(state: RecyclerView.State): Int

computeVerticalScrollOffset

open fun computeVerticalScrollOffset(state: RecyclerView.State): Int

computeVerticalScrollRange

open fun computeVerticalScrollRange(state: RecyclerView.State): Int

findFirstCompletelyVisibleItemPosition

open fun findFirstCompletelyVisibleItemPosition(): Int

Returns the adapter position of the first fully visible view. This position does not include adapter changes that were dispatched after the last layout pass.

Note that bounds check is only performed in the current orientation. That means, if LayoutManager is horizontal, it will only check the view's left and right edges.

Return
Int: The adapter position of the first fully visible item or RecyclerView#NO_POSITION if there aren't any visible items.

findFirstVisibleItemPosition

open fun findFirstVisibleItemPosition(): Int

Returns the adapter position of the first visible view. This position does not include adapter changes that were dispatched after the last layout pass.

Note that, this value is not affected by layout orientation or item order traversal. (setReverseLayout(boolean)). 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.

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

Return
Int: The adapter position of the first visible item or RecyclerView#NO_POSITION if there aren't any visible items.

findLastCompletelyVisibleItemPosition

open fun findLastCompletelyVisibleItemPosition(): Int

Returns the adapter position of the last fully visible view. This position does not include adapter changes that were dispatched after the last layout pass.

Note that bounds check is only performed in the current orientation. That means, if LayoutManager is horizontal, it will only check the view's left and right edges.

Return
Int: The adapter position of the last fully visible view or RecyclerView#NO_POSITION if there aren't any visible items.

findLastVisibleItemPosition

open fun findLastVisibleItemPosition(): Int

Returns the adapter position of the last visible view. This position does not include adapter changes that were dispatched after the last layout pass.

Note that, this value is not affected by layout orientation or item order traversal. (setReverseLayout(boolean)). 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.

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

Return
Int: The adapter position of the last visible view or RecyclerView#NO_POSITION if there aren't any visible items.

findViewByPosition

open fun findViewByPosition(position: Int): View?

Finds the view which represents the given adapter position.

This method traverses each child since it has no information about child order. Override this method to improve performance if your LayoutManager keeps data about child views.

If a view is ignored via ignoreView(View), it is also ignored by this method.

Parameters
position Int: Position of the item in adapter
Return
View?: The child view that represents the given position or null if the position is not laid out

generateDefaultLayoutParams

open fun generateDefaultLayoutParams(): RecyclerView.LayoutParams!

Create a default LayoutParams object for a child of the RecyclerView.

LayoutManagers will often want to use a custom LayoutParams type to store extra information specific to the layout. Client code should subclass RecyclerView.LayoutParams for this purpose.

Important: if you use your own custom LayoutParams type you must also override checkLayoutParams(LayoutParams), generateLayoutParams(android.view.ViewGroup.LayoutParams) and generateLayoutParams(android.content.Context, android.util.AttributeSet).

Return
RecyclerView.LayoutParams!: A new LayoutParams for a child view

getInitialPrefetchItemCount

open fun getInitialPrefetchItemCount(): Int

Gets the number of items to prefetch in collectInitialPrefetchPositions(int, LayoutPrefetchRegistry), which defines how many inner items should be prefetched when this LayoutManager's RecyclerView is nested inside another RecyclerView.

Return
Int: number of items to prefetch.

getOrientation

open fun getOrientation(): Int

Returns the current orientation of the layout.

Return
Int: Current orientation, either HORIZONTAL or VERTICAL

getRecycleChildrenOnDetach

open fun getRecycleChildrenOnDetach(): Boolean

Returns whether LayoutManager will recycle its children when it is detached from RecyclerView.

Return
Boolean: true if LayoutManager will recycle its children when it is detached from RecyclerView.

getReverseLayout

open fun getReverseLayout(): Boolean

Returns if views are laid out from the opposite direction of the layout.

Return
Boolean: If layout is reversed or not.

getStackFromEnd

open fun getStackFromEnd(): Boolean

isAutoMeasureEnabled

open fun isAutoMeasureEnabled(): Boolean

isSmoothScrollbarEnabled

open fun isSmoothScrollbarEnabled(): Boolean

Returns the current state of the smooth scrollbar feature. It is enabled by default.

Return
Boolean: True if smooth scrollbar is enabled, false otherwise.

onDetachedFromWindow

open fun onDetachedFromWindow(view: RecyclerView!, recycler: RecyclerView.Recycler!): Unit

onFocusSearchFailed

open fun onFocusSearchFailed(focused: View, focusDirection: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State): View?

onInitializeAccessibilityEvent

open fun onInitializeAccessibilityEvent(event: AccessibilityEvent): Unit

onLayoutChildren

open fun onLayoutChildren(recycler: RecyclerView.Recycler!, state: RecyclerView.State!): Unit

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 simple item animations are enabled. This means that add/remove operations on the adapter will result in animations to add new or appearing items, removed or disappearing items, and moved items. If a LayoutManager returns false from supportsPredictiveItemAnimations(), which is the default, and runs a normal layout operation during onLayoutChildren(Recycler, State), the RecyclerView will have enough information to run those animations in a simple way. For example, the default ItemAnimator, DefaultItemAnimator, will simply fade views in and out, whether they are actually added/removed or whether they are moved on or off the screen due to other add/remove operations.

A LayoutManager wanting a better item animation experience, where items can be animated onto and off of the screen according to where the items exist when they are not on screen, then the LayoutManager should return true from supportsPredictiveItemAnimations() and add additional logic to onLayoutChildren(Recycler, State). Supporting predictive animations means that onLayoutChildren(Recycler, State) will be called twice; once as a "pre" layout step to determine where items would have been prior to a 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 out appropriately. Also, removed items will be 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 used to help calculate correct positioning of other views, including views that were not previously onscreen (referred to as APPEARING views), but whose pre-layout offscreen position can be determined given the extra information about the pre-layout removed views.

The second layout pass is the real layout in which only non-removed views will be used. The only additional requirement during this pass is, if supportsPredictiveItemAnimations() returns true, to note which views exist in the child list prior to layout and which are not there after layout (referred to as DISAPPEARING views), and to position/layout those views appropriately, without regard to the actual bounds of the RecyclerView. This allows the animation system to know the location to which to animate these disappearing views.

The default LayoutManager implementations for RecyclerView handle all of these requirements for animations already. Clients of RecyclerView can either use one of these layout managers directly or look at their implementations of onLayoutChildren() to see how they account for the APPEARING and DISAPPEARING views.

Parameters
recycler RecyclerView.Recycler!: Recycler to use for fetching potentially cached views for a position
state RecyclerView.Recycler!: Transient state of RecyclerView

onLayoutCompleted

open fun onLayoutCompleted(state: RecyclerView.State!): Unit

onRestoreInstanceState

open fun onRestoreInstanceState(state: Parcelable!): Unit

onSaveInstanceState

open fun onSaveInstanceState(): Parcelable?

prepareForDrop

open fun prepareForDrop(@NonNull view: View, @NonNull target: View, x: Int, y: Int): Unit

Called by the ItemTouchHelper after a View is dropped over another View.

A LayoutManager should implement this interface to get ready for the upcoming move operation.

For example, LinearLayoutManager sets up a "scrollToPositionWithOffset" calls so that the View under drag will be used as an anchor View while calculating the next layout, making layout stay consistent.

Parameters
view View: The View which is being dragged. It is very likely that user is still dragging this View so there might be other calls to prepareForDrop() after this one.
target View: The target view which is being dropped on.
x View: The left offset of the View that is being dragged. This value includes the movement caused by the user.
y View: The top offset of the View that is being dragged. This value includes the movement caused by the user.

scrollHorizontallyBy

open fun scrollHorizontallyBy(dx: Int, recycler: RecyclerView.Recycler!, state: RecyclerView.State!): Int

Scroll horizontally by dx pixels in screen coordinates and return the distance traveled. The default implementation does nothing and returns 0.

Parameters
dx Int: distance to scroll by in pixels. X increases as scroll position approaches the right.
recycler Int: Recycler to use for fetching potentially cached views for a position
state Int: Transient state of RecyclerView
Return
Int: The actual distance scrolled. The return value will be negative if dx was negative and scrolling proceeeded in that direction. Math.abs(result) may be less than dx if a boundary was reached.

scrollToPosition

open fun scrollToPosition(position: Int): Unit

Scroll the RecyclerView to make the position visible.

RecyclerView will scroll the minimum amount that is necessary to make the target position visible. If you are looking for a similar behavior to android.widget.ListView#setSelection(int) or android.widget.ListView#setSelectionFromTop(int, int), use scrollToPositionWithOffset(int, int).

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

Parameters
position Int: Scroll to this adapter position

scrollToPositionWithOffset

open fun scrollToPositionWithOffset(position: Int, offset: Int): Unit

Scroll to the specified adapter position with the given offset from resolved layout start. Resolved layout start depends on getReverseLayout(), ViewCompat#getLayoutDirection(android.view.View) and getStackFromEnd().

For example, if layout is VERTICAL and getStackFromEnd() is true, calling scrollToPositionWithOffset(10, 20) will layout such that item[10]'s bottom is 20 pixels above the RecyclerView's bottom.

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(int).

Parameters
position Int: Index (starting at 0) of the reference item.
offset Int: The distance (in pixels) between the start edge of the item view and start edge of the RecyclerView.

scrollVerticallyBy

open fun scrollVerticallyBy(dy: Int, recycler: RecyclerView.Recycler!, state: RecyclerView.State!): Int

Scroll vertically by dy pixels in screen coordinates and return the distance traveled. The default implementation does nothing and returns 0.

Parameters
dy Int: distance to scroll in pixels. Y increases as scroll position approaches the bottom.
recycler Int: Recycler to use for fetching potentially cached views for a position
state Int: Transient state of RecyclerView
Return
Int: The actual distance scrolled. The return value will be negative if dy was negative and scrolling proceeeded in that direction. Math.abs(result) may be less than dy if a boundary was reached.

setInitialPrefetchItemCount

open fun setInitialPrefetchItemCount(itemCount: Int): Unit

Sets the number of items to prefetch in collectInitialPrefetchPositions(int, LayoutPrefetchRegistry), which defines how many inner items should be prefetched when this LayoutManager's RecyclerView is nested inside another RecyclerView.

Set this value to the number of items this inner LayoutManager will display when it is first scrolled into the viewport. RecyclerView will attempt to prefetch that number of items so they are ready, avoiding jank as the inner RecyclerView is scrolled into the viewport.

For example, take a vertically scrolling RecyclerView with horizontally scrolling inner RecyclerViews. The rows always have 4 items visible in them (or 5 if not aligned). Passing 4 to this method for each inner RecyclerView's LinearLayoutManager will enable RecyclerView's prefetching feature to do create/bind work for 4 views within a row early, before it is scrolled on screen, instead of just the default 2.

Calling this method does nothing unless the LayoutManager is in a RecyclerView nested in another RecyclerView.

Note: Setting this value to be larger than the number of views that will be visible in this view can incur unnecessary bind work, and an increase to the number of Views created and in active use.

Parameters
itemCount Int: Number of items to prefetch

setOrientation

open fun setOrientation(orientation: Int): Unit

Sets the orientation of the layout. LinearLayoutManager will do its best to keep scroll position.

Parameters
orientation Int: HORIZONTAL or VERTICAL

setRecycleChildrenOnDetach

open fun setRecycleChildrenOnDetach(recycleChildrenOnDetach: Boolean): Unit

Set whether LayoutManager will recycle its children when it is detached from RecyclerView.

If you are using a RecyclerView.RecycledViewPool, it might be a good idea to set this flag to true so that views will be available to other RecyclerViews immediately.

Note that, setting this flag will result in a performance drop if RecyclerView is restored.

Parameters
recycleChildrenOnDetach Boolean: Whether children should be recycled in detach or not.

setReverseLayout

open fun setReverseLayout(reverseLayout: Boolean): Unit

Used to reverse item traversal and layout order. This behaves similar to the layout change for RTL views. When set to true, first item is laid out at the end of the UI, second item is laid out before it etc. 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. If you are looking for the exact same behavior of android.widget.AbsListView#setStackFromBottom(boolean), use setStackFromEnd(boolean)

setSmoothScrollbarEnabled

open fun setSmoothScrollbarEnabled(enabled: Boolean): Unit

When smooth scrollbar is enabled, the position and size of the scrollbar thumb is computed based on the number of visible pixels in the visible items. This however assumes that all list items have similar or equal widths or heights (depending on list orientation). If you use a list in which items have different dimensions, the scrollbar will change appearance as the user scrolls through the list. To avoid this issue, you need to disable this property. When smooth scrollbar is disabled, the position and size of the scrollbar thumb is based solely on the number of items in the adapter and the position of the visible items inside the adapter. This provides a stable scrollbar as the user navigates through a list of items with varying widths / heights.

Parameters
enabled Boolean: Whether or not to enable smooth scrollbar.

setStackFromEnd

open fun setStackFromEnd(stackFromEnd: Boolean): Unit

Compatibility support for android.widget.AbsListView#setStackFromBottom(boolean)

smoothScrollToPosition

open fun smoothScrollToPosition(recyclerView: RecyclerView!, state: RecyclerView.State!, position: Int): Unit

supportsPredictiveItemAnimations

open fun supportsPredictiveItemAnimations(): Boolean

Protected methods

calculateExtraLayoutSpace

protected open fun calculateExtraLayoutSpace(@NonNull state: RecyclerView.State, @NonNull extraLayoutSpace: IntArray): Unit

Calculates the amount of extra space (in pixels) that should be laid out by and stores the result in extraLayoutSpace. extraLayoutSpace[0] should be used for the extra space at the top/left, and extraLayoutSpace[1] should be used for the extra space at the bottom/right (depending on the orientation). Thus, the side where it is applied is unaffected by (LTR vs RTL), getStackFromEnd() and . Negative values are ignored.

By default, LinearLayoutManager lays out 1 extra page of items while smooth scrolling, in the direction of the scroll, and no extra space is laid out in all other situations. You can override this method to implement your own custom pre-cache logic. Use RecyclerView.State#hasTargetScrollPosition() to find out if a smooth scroll to a position is in progress, and RecyclerView.State#getTargetScrollPosition() to find out which item it is scrolling to.

Note:Laying out extra items generally comes with significant performance cost. It's typically only desirable in places like smooth scrolling to an unknown location, where 1) the extra content helps LinearLayoutManager know in advance when its target is approaching, so it can decelerate early and smoothly and 2) while motion is continuous.

Extending the extra layout space is especially expensive if done while the user may change scrolling direction. In the default implementation, changing direction will cause the extra layout space to swap to the opposite side of the viewport, incurring many rebinds/recycles, unless the cache is large enough to handle it.

getExtraLayoutSpace

protected open fun getExtraLayoutSpace(state: RecyclerView.State!): Int

Deprecated: Use calculateExtraLayoutSpace(RecyclerView.State, int[]) instead.

Returns the amount of extra space that should be laid out by LayoutManager.

By default, LinearLayoutManager lays out 1 extra page of items while smooth scrolling and 0 otherwise. You can override this method to implement your custom layout pre-cache logic.

Note:Laying out invisible elements generally comes with significant performance cost. It's typically only desirable in places like smooth scrolling to an unknown location, where 1) the extra content helps LinearLayoutManager know in advance when its target is approaching, so it can decelerate early and smoothly and 2) while motion is continuous.

Extending the extra layout space is especially expensive if done while the user may change scrolling direction. Changing direction will cause the extra layout space to swap to the opposite side of the viewport, incurring many rebinds/recycles, unless the cache is large enough to handle it.

Return
Int: The extra space that should be laid out (in pixels).

isLayoutRTL

protected open fun isLayoutRTL(): Boolean