【Android应用开发】RecycleView API 翻译 (文档翻译)
.
RecyclerView
extends?ViewGroupimplements?ScrollingView?NestedScrollingChild
| java.lang.Object | |||
| ???? | android.view.View | ||
| ? | ???? | android.view.ViewGroup | |
| ? | ? | ???? | android.support.v7.widget.RecyclerView |
| Known Direct SubclassesHorizontalGridView,?VerticalGridView |
類概述
這個靈活可變的View組件提供了一個在有限的窗口界面顯示一個大數據集.
術語表:
- Adapter(適配器):?RecyclerView.Adapter?的子類,負責提供用于展示數據集中某條目數據的View組件.
- Position(位置):?適配器(Adapter)中的數據項目位置.
- Index(索引):?一個已經附加的子組件的索引在getChildAt(int)方法中使用. 與Position形成對比.
- Binding(綁定進程):?適配器中需要一個顯示Position對應的數據的子組件,Binding就是準備該子組件的進程.
- Recycle (view):?該View之前曾用于顯示指定適配器位置的數據,那么這個View可能會被放置在一個緩存中,以便可以在之后被復用去顯示同樣類型的數據.上述操作可以跳過布局文件的初始化加載或創建, 這樣就可以很大程度上提高應用的性能.
- Scrap (view):?在布局過程中,一個已經進入暫時分離狀態子組件.在不用完全從父類RecycleView中分離的情況下,該Scrap View可以被復用.如果組件被認為是作廢的,那么重新綁定數據與組件和改變適配器不是必須的,不用作出改變.
- Dirty (view):?一個子組件在顯示之前,必須被適配器(Adapter)重新綁定.
RecyclerView中的位置(Position):
RecyclerView 引入了一個附加的抽象層次在RecyclerView.Adapter?和RecyclerView.LayoutManager?之間,用于在布局計算時成批量地觀察數據集的變化. 這樣從追蹤Adapter(適配器)數據變化到計算動畫效果, 產生一個布局管理器(LayoutManager).它同樣對提升性能很有幫助,因為所有的組件綁定發生的同事時,避免沒有數據改變的組件重新綁定數據.
鑒于上述原因, 在 RecycleView 中有兩種類型的與Position相關的方法:
- 布局位置 (layout position): 最近的一次布局計算的項目位置. 這個位置(Position)是以布局管理器 (LayoutManager) 的角度來說的.
- 適配器位置 (adapter position): 適配器(Adapter)項目(Item)的位置. 這個位置(Position)是以適配器(Adapter)的角度來說的.
這兩個位置 (Position) 基本上是一樣的, 除了在分發?adapter.notify*??事件 和 計算更新的布局的時候不一樣.?
返回或者接收 布局位置(*LayoutPosition*) 的方法, 使用的位置是截止到最近的布局計算的位置 (例如?getLayoutPosition(),findViewHolderForLayoutPosition(int)). 這些位置會一直變化, 直到最近的布局計算完成. 你可以依賴這些位置, 這些位置與用戶當前在屏幕上看到的位置是一致的.例如, 如果你在屏幕上有一個項目列表, 用戶要求使用第五個項目元素, 你可以使用這些方法, 因為這些方法對應的位置就是用戶看到的位置.
另外一些關于 適配器位置(*AdapterPosition*)的方法 (例如: ?getAdapterPosition(),?findViewHolderForAdapterPosition(int)),?當你需要去使用最新的適配器位置時, 你應在使用這些方法, 即使這些位置還沒有針對對布局進行更新. 例如, 如果你觸發了 ViewHolder 點擊事件, 想要去獲取適配器中的項目元素, 你應該使用 getAdapterPosition()?方法. 注意這些方法可能不能去計算適配器的位置, 如果在?notifyDataSetChanged()?方法被調用, 同時新的布局在沒有被計算時. 鑒于以上原因, 你應該小心的去處理 方法返回?NO_POSITION?或者?null?結果的情況.
當你在重寫布局管理器?RecyclerView.LayoutManager?時, 你總是想要去獲取布局位置(Layout Position), 當你在重寫 適配器 RecyclerView.Adapter,?時, 你總是要獲取適配器位置 (adapter positions).
Summary
| class | RecyclerView.Adapter<VH?extends?RecyclerView.ViewHolder> | 適配器基類 |
| 適配器提供了一個功能, 可以綁定應用相關的數據集 與展示在 RecycleView 中的項目元素的?View 組件. | ||
| class | RecyclerView.AdapterDataObserver | 觀察 適配器 (RecycleView.Adapter) 變化的 觀察者基類. |
| interface | RecyclerView.ChildDrawingOrderCallback | 改變 RecycleView 子組件的 繪制順序的回調接口. |
| class | RecyclerView.ItemAnimator | 該類定義了條目發生改變時 適配器 的動畫效果. |
| class | RecyclerView.ItemDecoration | 項目裝飾, 在適配器數據集中指定的項目顯示組件上, 添加一個特別的圖畫 和 布局. |
| class | RecyclerView.LayoutManager | 布局管理器 (LayoutManager) 主要負責在 RecycleView 中測量和放置項目 View 組件, 同時決定當項目 View 組件對用戶不可見時回收 項目 View 組件的方案策略; |
| class | RecyclerView.LayoutParams | LayoutParams?的子類, 用于設置?RecycleView 子組件. |
| interface | RecyclerView.OnChildAttachStateChangeListener | 如果將該監聽器接口對象設置給 RecycleView 后, 當 ViewHolder 從 RecycleView 中被附加或者移除的時候該監聽器就會被通知. |
| interface | RecyclerView.OnItemTouchListener | 項目觸摸監聽器的作用 : RecycleView 的層級中觸摸事件被當做 RecycleView 自己的滾動操作, 設置了該監聽器, 就可以在 RecycleView 將觸摸事件當做滾動事件之前攔截這些觸摸操作.? |
| class | RecyclerView.OnScrollListener | 滾動監聽器 (OnScrollListener) 被設置給 RecycleView 后, ?當滾動事件被觸發時,?可以接收滾動相關的信息. |
| class | RecyclerView.RecycledViewPool | RecycleView 池 可以讓你在不同的 RecycleView 之間?分享 View 組件. |
| class | RecyclerView.Recycler | Recycler (復用器) 作用是管理 已銷毀 或者 被分離的 項目組件 以用于復用. |
| interface | RecyclerView.RecyclerListener | 循環復用監聽器 : 設置給 RecycleView 后, 當 View 組件被復用時, 會接收于此相關的信息. |
| class | RecyclerView.SimpleOnItemTouchListener | RecycleView.OnItemTouchListener 接口的實現類, 有一個空的方法體 和 默認返回值. |
| class | RecyclerView.SmoothScroller | 平滑滾動類的基類 |
| class | RecyclerView.State | 包含了一些 關于當前的 RecycleView 的狀態 的有用的信息, 如 目標滾動位置 和 View 組件 的焦點. |
| class | RecyclerView.ViewCacheExtension | ViewCacheExtension 是一個幫助類, 用于提供一個 可以被開發者 操縱的 View 緩存附加層. |
| class | RecyclerView.ViewHolder | 一個 ViewHolder 描述了一個條目組件 (View) 和要在 RecycleView 中的該位置顯示的元數據(metadata). |
| From class?android.view.ViewGroup | |||||||||||
| From class?android.view.View |
| Attribute Name | Related Method | Description |
| android.support.v7.recyclerview:layoutManager | ? | RecycleView 的布局管理器 |
| From class?android.view.View |
| From class?android.view.ViewGroup | |||||||||||
| From class?android.view.View |
| RecyclerView(Context?context) | |
| RecyclerView(Context?context,?AttributeSet?attrs) | |
| RecyclerView(Context?context,?AttributeSet?attrs, int defStyle) |
| void | addFocusables(ArrayList<View> views, int direction, int focusableMode)添加任意可獲取焦點的組件, 這些被添加的組件是該 View (調用本方法的 View 組件, 可能包括這個 View 本身也可以獲取焦點) 的子節點. |
| void | addItemDecoration(RecyclerView.ItemDecoration?decor)為這個 RecycleView 添加一個項目裝飾 (RecycleView.ItemDecoration). |
| void | addItemDecoration(RecyclerView.ItemDecoration?decor, int index)為這個 RecycleView 添加一個項目裝飾 (RecycleView.ItemDecoration). |
| void | addOnChildAttachStateChangeListener(RecyclerView.OnChildAttachStateChangeListener?listener)注冊一個監聽器, 當子組件被附加或者從 RecycleView 中移除時, 會得到一個相關的通知. |
| void | addOnItemTouchListener(RecyclerView.OnItemTouchListener?listener)添加一個項目觸摸監聽器用于監聽觸摸事件, 在這些事件被傳給子組件 或者 在 RecycleView 級別上被 當做滾動事件 前, 攔截這些事件. |
| void | addOnScrollListener(RecyclerView.OnScrollListener?listener)添加一個監聽器, 作用是當滾動狀態 或者 位置發生變化時得到相應的通知. |
| void | clearOnChildAttachStateChangeListeners()移除 通過 addOnChildAttachStateChangeListener 方法添加的監聽器. |
| void | clearOnScrollListeners()之前 設置的 關于通知任意滾動狀態 或 位置 變化的?監聽器, 該方法用于移除這些次要的監聽器. |
| int | computeHorizontalScrollExtent() 在水平范圍中, 計算水平滾動條的水平范圍. |
| int | computeHorizontalScrollOffset() 在水平范圍中, 計算水平滾動條的水平偏移量. |
| int | computeHorizontalScrollRange() 計算 橫向滾動條 在水平方向上的滾動范圍. |
| int | computeVerticalScrollExtent() 在垂直范圍內, 計算垂直滾動條翻越的范圍. |
| int | computeVerticalScrollOffset() 在垂直方向范圍中, 計算垂直方向上的 垂直滾動條 的翻越的偏移量. |
| int | computeVerticalScrollRange() 計算垂直滾動條的滾動范圍. |
| boolean | dispatchNestedFling(float velocityX, float velocityY, boolean consumed)分發拋出動作到嵌套的滑動中. |
| boolean | dispatchNestedPreFling(float velocityX, float velocityY)在動作被 View 組件處理前, 分發一個拋出動作到嵌套滑動中. |
| boolean | dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow)在 View 執行 滾動動作前, 分發一個嵌套滾動的步驟; |
| boolean | dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow)分發一個嵌套滾動中的一個步驟; |
| void | draw(Canvas?c)主要用于在給定的畫布中 渲染 View 組件 (及 View 組件的子組件) ; |
| boolean | drawChild(Canvas?canvas,?View?child, long drawingTime)繪制 View 組中的一個子組件; |
| View | findChildViewUnder(float x, float y)在給定的一點找出最頂端的 View 組件; |
| RecyclerView.ViewHolder | findViewHolderForAdapterPosition(int position)在數據集中, 通過給定的 位置, 找出 item 條目的 ViewHolder; |
| RecyclerView.ViewHolder | findViewHolderForItemId(long id)根據一個給定 item 的 id 編號找出其 ViewHolder; |
| RecyclerView.ViewHolder | findViewHolderForLayoutPosition(int position)根據給定的 最新 使用的布局 的位置 (也是數據集的位置) 返回對應的 item 條目的?ViewHolder; |
| RecyclerView.ViewHolder | findViewHolderForPosition(int position)該方法棄用, 使用 ?findViewHolderForLayoutPosition(int)?orfindViewHolderForAdapterPosition(int) |
| boolean | fling(int velocityX, int velocityY)給定一個初始的速度 (像素/秒) 沿著 對應的坐標軸 開始一個標準的拋出動作; |
| View | focusSearch(View?focused, int direction)在給定的方向上, 找出最近的 View 組件, 獲取焦點; |
| ViewGroup.LayoutParams | generateLayoutParams(AttributeSet?attrs)Returns a new set of layout parameters based on the supplied attributes set.基于給定的屬性集合, 返回一個新的布局參數; |
| Adapter | getAdapter()Retrieves the previously set adapter or null if no adapter is set. |
| int | getBaseline() Return the offset of the RecyclerView's text baseline from the its top boundary. |
| int | getChildAdapterPosition(View?child)Return the adapter position that the given child view corresponds to. |
| long | getChildItemId(View?child)Return the stable item id that the given child view corresponds to. |
| int | getChildLayoutPosition(View?child)Return the adapter position of the given child view as of the latest completed layout pass. |
| int | getChildPosition(View?child)This method is deprecated. use?getChildAdapterPosition(View)?or?getChildLayoutPosition(View). |
| RecyclerView.ViewHolder | getChildViewHolder(View?child)Retrieve the?RecyclerView.ViewHolder?for the given child view. |
| RecyclerViewAccessibilityDelegate | getCompatAccessibilityDelegate()Returns the accessibility delegate compatibility implementation used by the RecyclerView. |
| RecyclerView.ItemAnimator | getItemAnimator()Gets the current ItemAnimator for this RecyclerView. |
| RecyclerView.LayoutManager | getLayoutManager()Return the?RecyclerView.LayoutManager?currently responsible for layout policy for this RecyclerView. |
| int | getMaxFlingVelocity()Returns the maximum fling velocity used by this RecyclerView. |
| int | getMinFlingVelocity()Returns the minimum velocity to start a fling. |
| RecyclerView.RecycledViewPool | getRecycledViewPool()Retrieve this RecyclerView's?RecyclerView.RecycledViewPool. |
| int | getScrollState()Return the current scrolling state of the RecyclerView. |
| boolean | hasFixedSize() |
| boolean | hasNestedScrollingParent()Returns true if this view has a nested scrolling parent. |
| boolean | hasPendingAdapterUpdates()Returns whether there are pending adapter updates which are not yet applied to the layout. |
| void | invalidateItemDecorations()Invalidates all ItemDecorations. |
| boolean | isAnimating()Returns true if RecyclerView is currently running some animations. |
| boolean | isAttachedToWindow()Returns true if RecyclerView is attached to window. |
| boolean | isComputingLayout()Returns whether RecyclerView is currently computing a layout. |
| boolean | isLayoutFrozen()Returns true if layout and scroll are frozen. |
| boolean | isNestedScrollingEnabled()Returns true if nested scrolling is enabled for this view. |
| void | offsetChildrenHorizontal(int dx)Offset the bounds of all child views by?dx?pixels. |
| void | offsetChildrenVertical(int dy)Offset the bounds of all child views by?dy?pixels. |
| void | onChildAttachedToWindow(View?child)Called when an item view is attached to this RecyclerView. |
| void | onChildDetachedFromWindow(View?child)Called when an item view is detached from this RecyclerView. |
| void | onDraw(Canvas?c)Implement this to do your drawing. |
| boolean | onGenericMotionEvent(MotionEvent?event)Implement this method to handle generic motion events. |
| boolean | onInterceptTouchEvent(MotionEvent?e)Implement this method to intercept all touch screen motion events. |
| void | onScrollStateChanged(int state)Called when the scroll state of this RecyclerView changes. |
| void | onScrolled(int dx, int dy)Called when the scroll position of this RecyclerView changes. |
| boolean | onTouchEvent(MotionEvent?e)Implement this method to handle touch screen motion events. |
| void | removeItemDecoration(RecyclerView.ItemDecoration?decor)Remove an?RecyclerView.ItemDecoration?from this RecyclerView. |
| void | removeOnChildAttachStateChangeListener(RecyclerView.OnChildAttachStateChangeListener?listener)Removes the provided listener from child attached state listeners list. |
| void | removeOnItemTouchListener(RecyclerView.OnItemTouchListener?listener)Remove an?RecyclerView.OnItemTouchListener. |
| void | removeOnScrollListener(RecyclerView.OnScrollListener?listener)Remove a listener that was notified of any changes in scroll state or position. |
| void | requestChildFocus(View?child,?View?focused)Called when a child of this parent wants focus |
| boolean | requestChildRectangleOnScreen(View?child,?Rect?rect, boolean immediate)Called when a child of this group wants a particular rectangle to be positioned onto the screen. |
| void | requestDisallowInterceptTouchEvent(boolean disallowIntercept)Called when a child does not want this parent and its ancestors to intercept touch events withonInterceptTouchEvent(MotionEvent). |
| void | requestLayout()Call this when something has changed which has invalidated the layout of this view. |
| void | scrollBy(int x, int y)Move the scrolled position of your view. |
| void | scrollTo(int x, int y)Set the scrolled position of your view. |
| void | scrollToPosition(int position)Convenience method to scroll to a certain position. |
| void | sendAccessibilityEventUnchecked(AccessibilityEvent?event)This method behaves exactly as?sendAccessibilityEvent(int)?but takes as an argument an emptyAccessibilityEvent?and does not perform a check whether accessibility is enabled. |
| void | setAccessibilityDelegateCompat(RecyclerViewAccessibilityDelegate?accessibilityDelegate)Sets the accessibility delegate compatibility implementation used by RecyclerView. |
| void | setAdapter(Adapter?adapter)Set a new adapter to provide child views on demand. |
| void | setChildDrawingOrderCallback(RecyclerView.ChildDrawingOrderCallback?childDrawingOrderCallback)Sets the?RecyclerView.ChildDrawingOrderCallback?to be used for drawing children. |
| void | setClipToPadding(boolean clipToPadding)Sets whether this ViewGroup will clip its children to its padding and resize (but not clip) any EdgeEffect to the padded region, if padding is present. |
| void | setHasFixedSize(boolean hasFixedSize)RecyclerView can perform several optimizations if it can know in advance that changes in adapter content cannot change the size of the RecyclerView itself. |
| void | setItemAnimator(RecyclerView.ItemAnimator?animator)Sets the?RecyclerView.ItemAnimator?that will handle animations involving changes to the items in this RecyclerView. |
| void | setItemViewCacheSize(int size)Set the number of offscreen views to retain before adding them to the potentially shared?recycled view pool. |
| void | setLayoutFrozen(boolean frozen)Enable or disable layout and scroll. |
| void | setLayoutManager(RecyclerView.LayoutManager?layout)Set the?RecyclerView.LayoutManager?that this RecyclerView will use. |
| void | setNestedScrollingEnabled(boolean enabled)Enable or disable nested scrolling for this view. |
| void | setOnScrollListener(RecyclerView.OnScrollListener?listener)This method is deprecated. Use?addOnScrollListener(OnScrollListener)?andremoveOnScrollListener(OnScrollListener) |
| void | setRecycledViewPool(RecyclerView.RecycledViewPool?pool)Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. |
| void | setRecyclerListener(RecyclerView.RecyclerListener?listener)Register a listener that will be notified whenever a child view is recycled. |
| void | setScrollingTouchSlop(int slopConstant)Configure the scrolling touch slop for a specific use case. |
| void | setViewCacheExtension(RecyclerView.ViewCacheExtension?extension)Sets a new?RecyclerView.ViewCacheExtension?to be used by the Recycler. |
| void | smoothScrollBy(int dx, int dy)Animate a scroll by the given amount of pixels along either axis. |
| void | smoothScrollToPosition(int position)Starts a smooth scroll to an adapter position. |
| boolean | startNestedScroll(int axes)Begin a nestable scroll operation along the given axes. |
| void | stopNestedScroll()Stop a nested scroll in progress. |
| void | stopScroll()Stop any current scroll in progress, such as one started by?smoothScrollBy(int, int),?fling(int, int)?or a touch-initiated fling. |
| void | swapAdapter(Adapter?adapter, boolean removeAndRecycleExistingViews)Swaps the current adapter with the provided one. |
| boolean | checkLayoutParams(ViewGroup.LayoutParams?p) |
| void | dispatchRestoreInstanceState(SparseArray<Parcelable> container)Override to prevent thawing of any views created by the adapter. |
| void | dispatchSaveInstanceState(SparseArray<Parcelable> container)Override to prevent freezing of any views created by the adapter. |
| ViewGroup.LayoutParams | generateDefaultLayoutParams()Returns a set of default layout parameters. |
| ViewGroup.LayoutParams | generateLayoutParams(ViewGroup.LayoutParams?p)Returns a safe set of layout parameters based on the supplied layout params. |
| int | getChildDrawingOrder(int childCount, int i)Returns the index of the child to draw for this iteration. |
| void | onAttachedToWindow()This is called when the view is attached to a window. |
| void | onDetachedFromWindow()This is called when the view is detached from a window. |
| void | onLayout(boolean changed, int l, int t, int r, int b)Called from layout when this view should assign a size and position to each of its children. |
| void | onMeasure(int widthSpec, int heightSpec) Measure the view and its content to determine the measured width and the measured height. |
| void | onRestoreInstanceState(Parcelable?state)Hook allowing a view to re-apply a representation of its internal state that had previously been generated byonSaveInstanceState(). |
| Parcelable | onSaveInstanceState()Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. |
| void | onSizeChanged(int w, int h, int oldw, int oldh)This is called during layout when the size of this view has changed. |
| void | removeDetachedView(View?child, boolean animate)Finishes the removal of a detached view. |
| ?From class?android.view.ViewGroup | |||||||||||
| ?From class?android.view.View | |||||||||||
| ?From class?java.lang.Object | |||||||||||
| ?From interface?android.view.ViewParent | |||||||||||
| ?From interface?android.view.ViewManager | |||||||||||
| ?From interface?android.graphics.drawable.Drawable.Callback | |||||||||||
| ?From interface?android.view.KeyEvent.Callback | |||||||||||
| ?From interface?android.view.accessibility.AccessibilityEventSource | |||||||||||
| ?From interface?android.support.v4.view.ScrollingView | |||||||||||
| ?From interface?android.support.v4.view.NestedScrollingChild |
XML Attributes
android.support.v7.recyclerview:layoutManager
Class name of the Layout Manager to be used.
The class must extend android.support.v7.widget.RecyclerView$LayoutManager and have either a default constructor or constructor with the signature (android.content.Context, android.util.AttributeSet, int, int).
If the name starts with a '.', application package is prefixed. Else, if the name contains a '.', the classname is assumed to be a full class name. Else, the recycler view package name (android.support.v7.widget) is prefixed.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This is a private symbol.
Related Methods
Constants
public static final int?HORIZONTAL
Constant Value:?0 (0x00000000)public static final int?INVALID_TYPE
Constant Value:?-1 (0xffffffff)public static final long?NO_ID
Constant Value:?-1 (0xffffffffffffffff)public static final int?NO_POSITION
Constant Value:?-1 (0xffffffff)public static final int?SCROLL_STATE_DRAGGING
The RecyclerView is currently being dragged by outside input such as user touch input.
See Also
- getScrollState()
public static final int?SCROLL_STATE_IDLE
The RecyclerView is not currently scrolling.
See Also
- getScrollState()
public static final int?SCROLL_STATE_SETTLING
The RecyclerView is currently animating to a final position while not under outside control.
See Also
- getScrollState()
public static final int?TOUCH_SLOP_DEFAULT
Constant for use with?setScrollingTouchSlop(int). Indicates that the RecyclerView should use the standard touch slop for smooth, continuous scrolling.
Constant Value:?0 (0x00000000)public static final int?TOUCH_SLOP_PAGING
Constant for use with?setScrollingTouchSlop(int). Indicates that the RecyclerView should use the standard touch slop for scrolling widgets that snap to a page or other coarse-grained barrier.
Constant Value:?1 (0x00000001)public static final int?VERTICAL
Constant Value:?1 (0x00000001)Public Constructors
public?RecyclerView?(Context?context)
public?RecyclerView?(Context?context,?AttributeSet?attrs)
public?RecyclerView?(Context?context,?AttributeSet?attrs, int defStyle)
Public Methods
public void?addFocusables?(ArrayList<View> views, int direction, int focusableMode)
Adds any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views. This method adds all focusable views regardless if we are in touch mode or only views focusable in touch mode if we are in touch mode or only views that can take accessibility focus if accessibility is enabled depending on the focusable mode parameter.
Parameters
| Focusable views found so far or null if all we are interested is the number of focusables. |
| The direction of the focus. |
| The type of focusables to be added. |
public void?addItemDecoration?(RecyclerView.ItemDecoration?decor)
Add an?RecyclerView.ItemDecoration?to this RecyclerView. Item decorations can affect both measurement and drawing of individual item views.
Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.
Parameters
| Decoration to add |
public void?addItemDecoration?(RecyclerView.ItemDecoration?decor, int index)
Add an?RecyclerView.ItemDecoration?to this RecyclerView. Item decorations can affect both measurement and drawing of individual item views.
Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.
Parameters
| Decoration to add |
| Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end. |
public void?addOnChildAttachStateChangeListener?(RecyclerView.OnChildAttachStateChangeListener?listener)
Register a listener that will be notified whenever a child view is attached to or detached from RecyclerView.
This listener will be called when a LayoutManager or the RecyclerView decides that a child view is no longer needed. If an application associates expensive or heavyweight data with item views, this may be a good place to release or free those resources.
Parameters
| Listener to register |
public void?addOnItemTouchListener?(RecyclerView.OnItemTouchListener?listener)
Add an?RecyclerView.OnItemTouchListener?to intercept touch events before they are dispatched to child views or this view's standard scrolling behavior.
Client code may use listeners to implement item manipulation behavior. Once a listener returns true from?onInterceptTouchEvent(RecyclerView, MotionEvent)?itsonTouchEvent(RecyclerView, MotionEvent)?method will be called for each incoming MotionEvent until the end of the gesture.
Parameters
| Listener to add |
See Also
- RecyclerView.SimpleOnItemTouchListener
public void?addOnScrollListener?(RecyclerView.OnScrollListener?listener)
Add a listener that will be notified of any changes in scroll state or position.
Components that add a listener should take care to remove it when finished. Other components that take ownership of a view may call?clearOnScrollListeners()to remove all attached listeners.
Parameters
| listener to set or null to clear |
public void?clearOnChildAttachStateChangeListeners?()
Removes all listeners that were added via?addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener).
public void?clearOnScrollListeners?()
Remove all secondary listener that were notified of any changes in scroll state or position.
public int?computeHorizontalScrollExtent?()
Compute the horizontal extent of the horizontal scrollbar's thumb within the horizontal range. This value is used to compute the length of the thumb within the scrollbar's track.
The range is expressed in arbitrary units that must be the same as the units used by?computeHorizontalScrollRange()?and?computeHorizontalScrollOffset().
Default implementation returns 0.
If you want to support scroll bars, override?computeHorizontalScrollExtent(RecyclerView.State)?in your LayoutManager.
Returns
- The horizontal extent of the scrollbar's thumb
See Also
- computeHorizontalScrollExtent(RecyclerView.State)
public int?computeHorizontalScrollOffset?()
Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range. This value is used to compute the length of the thumb within the scrollbar's track.
The range is expressed in arbitrary units that must be the same as the units used by?computeHorizontalScrollRange()?and?computeHorizontalScrollExtent().
Default implementation returns 0.
If you want to support scroll bars, override?computeHorizontalScrollOffset(RecyclerView.State)?in your LayoutManager.
Returns
- The horizontal offset of the scrollbar's thumb
See Also
- (RecyclerView.Adapter)
public int?computeHorizontalScrollRange?()
Compute the horizontal range that the horizontal scrollbar represents.
The range is expressed in arbitrary units that must be the same as the units used by?computeHorizontalScrollExtent()?and?computeHorizontalScrollOffset().
Default implementation returns 0.
If you want to support scroll bars, override?computeHorizontalScrollRange(RecyclerView.State)?in your LayoutManager.
Returns
- The total horizontal range represented by the vertical scrollbar
See Also
- computeHorizontalScrollRange(RecyclerView.State)
public int?computeVerticalScrollExtent?()
Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. This value is used to compute the length of the thumb within the scrollbar's track.
The range is expressed in arbitrary units that must be the same as the units used by?computeVerticalScrollRange()?and?computeVerticalScrollOffset().
Default implementation returns 0.
If you want to support scroll bars, override?computeVerticalScrollExtent(RecyclerView.State)?in your LayoutManager.
Returns
- The vertical extent of the scrollbar's thumb
See Also
- computeVerticalScrollExtent(RecyclerView.State)
public int?computeVerticalScrollOffset?()
Compute the vertical offset of the vertical scrollbar's thumb within the vertical range. This value is used to compute the length of the thumb within the scrollbar's track.
The range is expressed in arbitrary units that must be the same as the units used by?computeVerticalScrollRange()?and?computeVerticalScrollExtent().
Default implementation returns 0.
If you want to support scroll bars, override?computeVerticalScrollOffset(RecyclerView.State)?in your LayoutManager.
Returns
- The vertical offset of the scrollbar's thumb
See Also
- (RecyclerView.Adapter)
public int?computeVerticalScrollRange?()
Compute the vertical range that the vertical scrollbar represents.
The range is expressed in arbitrary units that must be the same as the units used by?computeVerticalScrollExtent()?and?computeVerticalScrollOffset().
Default implementation returns 0.
If you want to support scroll bars, override?computeVerticalScrollRange(RecyclerView.State)?in your LayoutManager.
Returns
- The total vertical range represented by the vertical scrollbar
See Also
- computeVerticalScrollRange(RecyclerView.State)
public boolean?dispatchNestedFling?(float velocityX, float velocityY, boolean consumed)
Dispatch a fling to a nested scrolling parent.
This method should be used to indicate that a nested scrolling child has detected suitable conditions for a fling. Generally this means that a touch scroll has ended with a?velocity?in the direction of scrolling that meets or exceeds the?minimum fling velocity?along a scrollable axis.
If a nested scrolling child view would normally fling but it is at the edge of its own content, it can use this method to delegate the fling to its nested scrolling parent instead. The parent may optionally consume the fling or observe a child fling.
Parameters
| Horizontal fling velocity in pixels per second |
| Vertical fling velocity in pixels per second |
| true if the child consumed the fling, false otherwise |
Returns
- true if the nested scrolling parent consumed or otherwise reacted to the fling
public boolean?dispatchNestedPreFling?(float velocityX, float velocityY)
Dispatch a fling to a nested scrolling parent before it is processed by this view.
Nested pre-fling events are to nested fling events what touch intercept is to touch and what nested pre-scroll is to nested scroll.?dispatchNestedPreFling?offsets an opportunity for the parent view in a nested fling to fully consume the fling before the child view consumes it. If this method returns?true, a nested parent view consumed the fling and this view should not scroll as a result.
For a better user experience, only one view in a nested scrolling chain should consume the fling at a time. If a parent view consumed the fling this method will return false. Custom view implementations should account for this in two ways:
- If a custom view is paged and needs to settle to a fixed page-point, do not call?dispatchNestedPreFling; consume the fling and settle to a valid position regardless.
- If a nested parent does consume the fling, this view should not scroll at all, even to settle back to a valid idle position.
Views should also not offer fling velocities to nested parent views along an axis where scrolling is not currently supported; a?ScrollView?should not offer a horizontal fling velocity to its parents since scrolling along that axis is not permitted and carrying velocity along that motion does not make sense.
Parameters
| Horizontal fling velocity in pixels per second |
| Vertical fling velocity in pixels per second |
Returns
- true if a nested scrolling parent consumed the fling
public boolean?dispatchNestedPreScroll?(int dx, int dy, int[] consumed, int[] offsetInWindow)
Dispatch one step of a nested scroll in progress before this view consumes any portion of it.
Nested pre-scroll events are to nested scroll events what touch intercept is to touch.?dispatchNestedPreScroll?offers an opportunity for the parent view in a nested scrolling operation to consume some or all of the scroll operation before the child view consumes it.
Parameters
| Horizontal scroll distance in pixels |
| Vertical scroll distance in pixels |
| Output. If not null, consumed[0] will contain the consumed component of dx and consumed[1] the consumed dy. |
| Optional. If not null, on return this will contain the offset in local view coordinates of this view from before this operation to after it completes. View implementations may use this to adjust expected input coordinate tracking. |
Returns
- true if the parent consumed some or all of the scroll delta
public boolean?dispatchNestedScroll?(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow)
Dispatch one step of a nested scroll in progress.
Implementations of views that support nested scrolling should call this to report info about a scroll in progress to the current nested scrolling parent. If a nested scroll is not currently in progress or nested scrolling is not?enabled?for this view this method does nothing.
Compatible View implementations should also call?dispatchNestedPreScroll?before consuming a component of the scroll event themselves.
Parameters
| Horizontal distance in pixels consumed by this view during this scroll step |
| Vertical distance in pixels consumed by this view during this scroll step |
| Horizontal scroll distance in pixels not consumed by this view |
| Horizontal scroll distance in pixels not consumed by this view |
| Optional. If not null, on return this will contain the offset in local view coordinates of this view from before this operation to after it completes. View implementations may use this to adjust expected input coordinate tracking. |
Returns
- true if the event was dispatched, false if it could not be dispatched.
public void?draw?(Canvas?c)
Manually render this view (and all of its children) to the given Canvas. The view must have already done a full layout before this function is called. When implementing a view, implement?onDraw(android.graphics.Canvas)?instead of overriding this method. If you do need to override this method, call the superclass version.
Parameters
| The Canvas to which the View is rendered. |
public boolean?drawChild?(Canvas?canvas,?View?child, long drawingTime)
Draw one child of this View Group. This method is responsible for getting the canvas in the right state. This includes clipping, translating so that the child's scrolled origin is at 0, 0, and applying any animation transformations.
Parameters
| The canvas on which to draw the child |
| Who to draw |
| The time at which draw is occurring |
Returns
- True if an invalidate() was issued
public?View?findChildViewUnder?(float x, float y)
Find the topmost view under the given point.
Parameters
| Horizontal position in pixels to search |
| Vertical position in pixels to search |
Returns
- The child view under (x, y) or null if no matching child is found
public?RecyclerView.ViewHolder?findViewHolderForAdapterPosition?(int position)
Return the ViewHolder for the item in the given position of the data set. Unlike?findViewHolderForLayoutPosition(int)?this method takes into account any pending adapter changes that may not be reflected to the layout yet. On the other hand, if?notifyDataSetChanged()?has been called but the new layout has not been calculated yet, this method will return?null?since the new positions of views are unknown until the layout is calculated.
This method checks only the children of RecyclerView. If the item at the given?position?is not laid out, it?will not?create a new one.
Parameters
| The position of the item in the data set of the adapter |
Returns
- The ViewHolder at?position?or null if there is no such item
public?RecyclerView.ViewHolder?findViewHolderForItemId?(long id)
Return the ViewHolder for the item with the given id. The RecyclerView must use an Adapter with?stableIds?to return a non-null value.
This method checks only the children of RecyclerView. If the item with the given?id?is not laid out, it?will not?create a new one.
Parameters
| The id for the requested item |
Returns
- The ViewHolder with the given?id?or null if there is no such item
public?RecyclerView.ViewHolder?findViewHolderForLayoutPosition?(int position)
Return the ViewHolder for the item in the given position of the data set as of the latest layout pass.
This method checks only the children of RecyclerView. If the item at the given?position?is not laid out, it?will not?create a new one.
Note that when Adapter contents change, ViewHolder positions are not updated until the next layout calculation. If there are pending adapter updates, the return value of this method may not match your adapter contents. You can use #getAdapterPosition()?to get the current adapter position of a ViewHolder.
Parameters
| The position of the item in the data set of the adapter |
Returns
- The ViewHolder at?position?or null if there is no such item
public?RecyclerView.ViewHolder?findViewHolderForPosition?(int position)
This method is deprecated.
use?findViewHolderForLayoutPosition(int)?or?findViewHolderForAdapterPosition(int)
public boolean?fling?(int velocityX, int velocityY)
Begin a standard fling with an initial velocity along each axis in pixels per second. If the velocity given is below the system-defined minimum this method will return false and no fling will occur.
Parameters
| Initial horizontal velocity in pixels per second |
| Initial vertical velocity in pixels per second |
Returns
- true if the fling was started, false if the velocity was too low to fling or LayoutManager does not support scrolling in the axis fling is issued.
See Also
- canScrollVertically()
- canScrollHorizontally()
public?View?focusSearch?(View?focused, int direction)
Find the nearest view in the specified direction that wants to take focus.
Parameters
| The view that currently has focus |
| One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT, or 0 for not applicable. |
public?ViewGroup.LayoutParams?generateLayoutParams?(AttributeSet?attrs)
Returns a new set of layout parameters based on the supplied attributes set.
Parameters
| the attributes to build the layout parameters from |
Returns
- an instance of?ViewGroup.LayoutParams?or one of its descendants
public?Adapter?getAdapter?()
Retrieves the previously set adapter or null if no adapter is set.
Returns
- The previously set adapter
See Also
- setAdapter(Adapter)
public int?getBaseline?()
Return the offset of the RecyclerView's text baseline from the its top boundary. If the LayoutManager of this RecyclerView does not support baseline alignment, this method returns -1.
Returns
- the offset of the baseline within the RecyclerView's bounds or -1 if baseline alignment is not supported
public int?getChildAdapterPosition?(View?child)
Return the adapter position that the given child view corresponds to.
Parameters
| Child View to query |
Returns
- Adapter position corresponding to the given view or?NO_POSITION
public long?getChildItemId?(View?child)
Return the stable item id that the given child view corresponds to.
Parameters
| Child View to query |
Returns
- Item id corresponding to the given view or?NO_ID
public int?getChildLayoutPosition?(View?child)
Return the adapter position of the given child view as of the latest completed layout pass.
This position may not be equal to Item's adapter position if there are pending changes in the adapter which have not been reflected to the layout yet.
Parameters
| Child View to query |
Returns
- Adapter position of the given View as of last layout pass or?NO_POSITION?if the View is representing a removed item.
public int?getChildPosition?(View?child)
This method is deprecated.
use?getChildAdapterPosition(View)?or?getChildLayoutPosition(View).
public?RecyclerView.ViewHolder?getChildViewHolder?(View?child)
Retrieve the?RecyclerView.ViewHolder?for the given child view.
Parameters
| Child of this RecyclerView to query for its ViewHolder |
Returns
- The child view's ViewHolder
public?RecyclerViewAccessibilityDelegate?getCompatAccessibilityDelegate?()
Returns the accessibility delegate compatibility implementation used by the RecyclerView.
Returns
- An instance of AccessibilityDelegateCompat used by RecyclerView
public?RecyclerView.ItemAnimator?getItemAnimator?()
Gets the current ItemAnimator for this RecyclerView. A null return value indicates that there is no animator and that item changes will happen without any animations. By default, RecyclerView instantiates and uses an instance of?DefaultItemAnimator.
Returns
- ItemAnimator The current ItemAnimator. If null, no animations will occur when changes occur to the items in this RecyclerView.
public?RecyclerView.LayoutManager?getLayoutManager?()
Return the?RecyclerView.LayoutManager?currently responsible for layout policy for this RecyclerView.
Returns
- The currently bound LayoutManager
public int?getMaxFlingVelocity?()
Returns the maximum fling velocity used by this RecyclerView.
Returns
- The maximum fling velocity used by this RecyclerView.
public int?getMinFlingVelocity?()
Returns the minimum velocity to start a fling.
Returns
- The minimum velocity to start a fling
public?RecyclerView.RecycledViewPool?getRecycledViewPool?()
Retrieve this RecyclerView's?RecyclerView.RecycledViewPool. This method will never return null; if no pool is set for this view a new one will be created. SeesetRecycledViewPool?for more information.
Returns
- The pool used to store recycled item views for reuse.
See Also
- setRecycledViewPool(RecycledViewPool)
public int?getScrollState?()
Return the current scrolling state of the RecyclerView.
Returns
- SCROLL_STATE_IDLE,?SCROLL_STATE_DRAGGING?or?SCROLL_STATE_SETTLING
public boolean?hasFixedSize?()
Returns
- true if the app has specified that changes in adapter content cannot change the size of the RecyclerView itself.
public boolean?hasNestedScrollingParent?()
Returns true if this view has a nested scrolling parent.
The presence of a nested scrolling parent indicates that this view has initiated a nested scroll and it was accepted by an ancestor view further up the view hierarchy.
Returns
- whether this view has a nested scrolling parent
public boolean?hasPendingAdapterUpdates?()
Returns whether there are pending adapter updates which are not yet applied to the layout.
If this method returns?true, it means that what user is currently seeing may not reflect them adapter contents (depending on what has changed). You may use this information to defer or cancel some operations.
This method returns true if RecyclerView has not yet calculated the first layout after it is attached to the Window or the Adapter has been replaced.
Returns
- True if there are some adapter updates which are not yet reflected to layout or false if layout is up to date.
public void?invalidateItemDecorations?()
Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method will trigger a?requestLayout()?call.
public boolean?isAnimating?()
Returns true if RecyclerView is currently running some animations.
If you want to be notified when animations are finished, use?isRunning(ItemAnimator.ItemAnimatorFinishedListener).
Returns
- True if there are some item animations currently running or waiting to be started.
public boolean?isAttachedToWindow?()
Returns true if RecyclerView is attached to window.
public boolean?isComputingLayout?()
Returns whether RecyclerView is currently computing a layout.
If this method returns true, it means that RecyclerView is in a lockdown state and any attempt to update adapter contents will result in an exception because adapter contents cannot be changed while RecyclerView is trying to compute the layout.
It is very unlikely that your code will be running during this state as it is called by the framework when a layout traversal happens or RecyclerView starts to scroll in response to system events (touch, accessibility etc).
This case may happen if you have some custom logic to change adapter contents in response to a View callback (e.g. focus change callback) which might be triggered during a layout calculation. In these cases, you should just postpone the change using a Handler or a similar mechanism.
Returns
- true?if RecyclerView is currently computing a layout,?false?otherwise
public boolean?isLayoutFrozen?()
Returns true if layout and scroll are frozen.
Returns
- true if layout and scroll are frozen
See Also
- setLayoutFrozen(boolean)
public boolean?isNestedScrollingEnabled?()
Returns true if nested scrolling is enabled for this view.
If nested scrolling is enabled and this View class implementation supports it, this view will act as a nested scrolling child view when applicable, forwarding data about the scroll operation in progress to a compatible and cooperating nested scrolling parent.
Returns
- true if nested scrolling is enabled
public void?offsetChildrenHorizontal?(int dx)
Offset the bounds of all child views by?dx?pixels. Useful for implementing simple scrolling in?LayoutManagers.
Parameters
| Horizontal pixel offset to apply to the bounds of all child views |
public void?offsetChildrenVertical?(int dy)
Offset the bounds of all child views by?dy?pixels. Useful for implementing simple scrolling in?LayoutManagers.
Parameters
| Vertical pixel offset to apply to the bounds of all child views |
public void?onChildAttachedToWindow?(View?child)
Called when an item view is attached to this RecyclerView.
Subclasses of RecyclerView may want to perform extra bookkeeping or modifications of child views as they become attached. This will be called before aRecyclerView.LayoutManager?measures or lays out the view and is a good time to perform these changes.
Parameters
| Child view that is now attached to this RecyclerView and its associated window |
public void?onChildDetachedFromWindow?(View?child)
Called when an item view is detached from this RecyclerView.
Subclasses of RecyclerView may want to perform extra bookkeeping or modifications of child views as they become detached. This will be called as aRecyclerView.LayoutManager?fully detaches the child view from the parent and its window.
Parameters
| Child view that is now detached from this RecyclerView and its associated window |
public void?onDraw?(Canvas?c)
Implement this to do your drawing.
Parameters
| the canvas on which the background will be drawn |
public boolean?onGenericMotionEvent?(MotionEvent?event)
Implement this method to handle generic motion events.
Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The?source?of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.
Generic motion events with source class?SOURCE_CLASS_POINTER?are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.
?public boolean onGenericMotionEvent(MotionEvent event) {if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {if (event.getAction() == MotionEvent.ACTION_MOVE) {// process the joystick movement...return true;}}if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {switch (event.getAction()) {case MotionEvent.ACTION_HOVER_MOVE:// process the mouse hover movement...return true;case MotionEvent.ACTION_SCROLL:// process the scroll wheel movement...return true;}}return super.onGenericMotionEvent(event);}Parameters
| The generic motion event being processed. |
Returns
- True if the event was handled, false otherwise.
public boolean?onInterceptTouchEvent?(MotionEvent?e)
Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.
Using this function takes some care, as it has a fairly complicated interaction with?View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:
Parameters
| The motion event being dispatched down the hierarchy. |
Returns
- Return true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.
public void?onScrollStateChanged?(int state)
Called when the scroll state of this RecyclerView changes. Subclasses should use this method to respond to state changes instead of an explicit listener.
This method will always be invoked before listeners, but after the LayoutManager responds to the scroll state change.
Parameters
| the new scroll state, one of?SCROLL_STATE_IDLE,?SCROLL_STATE_DRAGGING?or?SCROLL_STATE_SETTLING |
public void?onScrolled?(int dx, int dy)
Called when the scroll position of this RecyclerView changes. Subclasses should use this method to respond to scrolling within the adapter's data set instead of an explicit listener.
This method will always be invoked before listeners. If a subclass needs to perform any additional upkeep or bookkeeping after scrolling but before listeners run, this is a good place to do so.
This differs from?onScrollChanged(int, int, int, int)?in that it receives the distance scrolled in either direction within the adapter's data set instead of absolute scroll coordinates. Since RecyclerView cannot compute the absolute scroll position from any arbitrary point in the data set,?onScrollChanged?will always receive the current?getScrollX()?and?getScrollY()?values which do not correspond to the data set scroll position. However, some subclasses may choose to use these fields as special offsets.
Parameters
| horizontal distance scrolled in pixels |
| vertical distance scrolled in pixels |
public boolean?onTouchEvent?(MotionEvent?e)
Implement this method to handle touch screen motion events.
If this method is used to detect click actions, it is recommended that the actions be performed by implementing and calling?performClick(). This will ensure consistent system behavior, including:
- obeying click sound preferences
- dispatching OnClickListener calls
- handling?ACTION_CLICK?when accessibility features are enabled
Parameters
| The motion event. |
Returns
- True if the event was handled, false otherwise.
public void?removeItemDecoration?(RecyclerView.ItemDecoration?decor)
Remove an?RecyclerView.ItemDecoration?from this RecyclerView.
The given decoration will no longer impact the measurement and drawing of item views.
Parameters
| Decoration to remove |
See Also
- addItemDecoration(ItemDecoration)
public void?removeOnChildAttachStateChangeListener?(RecyclerView.OnChildAttachStateChangeListener?listener)
Removes the provided listener from child attached state listeners list.
Parameters
| Listener to unregister |
public void?removeOnItemTouchListener?(RecyclerView.OnItemTouchListener?listener)
Remove an?RecyclerView.OnItemTouchListener. It will no longer be able to intercept touch events.
Parameters
| Listener to remove |
public void?removeOnScrollListener?(RecyclerView.OnScrollListener?listener)
Remove a listener that was notified of any changes in scroll state or position.
Parameters
| listener to set or null to clear |
public void?requestChildFocus?(View?child,?View?focused)
Called when a child of this parent wants focus
Parameters
| The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus. |
| The view that is a descendant of child that actually has focus |
public boolean?requestChildRectangleOnScreen?(View?child,?Rect?rect, boolean immediate)
Called when a child of this group wants a particular rectangle to be positioned onto the screen.?ViewGroups overriding this can trust that:
- child will be a direct child of this group
- rectangle will be in the child's coordinates
ViewGroups overriding this should uphold the contract:
- nothing will change if the rectangle is already visible
- the view port will be scrolled only just enough to make the rectangle visible
Parameters
| The direct child making the request. |
| The rectangle in the child's coordinates the child wishes to be on the screen. |
| True to forbid animated or delayed scrolling, false otherwise |
Returns
- Whether the group scrolled to handle the operation
public void?requestDisallowInterceptTouchEvent?(boolean disallowIntercept)
Called when a child does not want this parent and its ancestors to intercept touch events with?onInterceptTouchEvent(MotionEvent).
This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.
Parameters
| True if the child does not want the parent to intercept touch events. |
public void?requestLayout?()
Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.
Subclasses which override this method should call the superclass method to handle possible request-during-layout errors correctly.
public void?scrollBy?(int x, int y)
Move the scrolled position of your view. This will cause a call to?onScrollChanged(int, int, int, int)?and the view will be invalidated.
Parameters
| the amount of pixels to scroll by horizontally |
| the amount of pixels to scroll by vertically |
public void?scrollTo?(int x, int y)
Set the scrolled position of your view. This will cause a call to?onScrollChanged(int, int, int, int)?and the view will be invalidated.
Parameters
| the x position to scroll to |
| the y position to scroll to |
public void?scrollToPosition?(int position)
Convenience method to scroll to a certain position. RecyclerView does not implement scrolling logic, rather forwards the call to?scrollToPosition(int)
Parameters
| Scroll to this adapter position |
See Also
- scrollToPosition(int)
public void?sendAccessibilityEventUnchecked?(AccessibilityEvent?event)
This method behaves exactly as?sendAccessibilityEvent(int)?but takes as an argument an empty?AccessibilityEvent?and does not perform a check whether accessibility is enabled.
If an?View.AccessibilityDelegate?has been specified via calling?setAccessibilityDelegate(AccessibilityDelegate)?itssendAccessibilityEventUnchecked(View, AccessibilityEvent)?is responsible for handling this call.
Parameters
| The event to send. |
public void?setAccessibilityDelegateCompat?(RecyclerViewAccessibilityDelegate?accessibilityDelegate)
Sets the accessibility delegate compatibility implementation used by RecyclerView.
Parameters
| The accessibility delegate to be used by RecyclerView. |
public void?setAdapter?(Adapter?adapter)
Set a new adapter to provide child views on demand.
When adapter is changed, all existing views are recycled back to the pool. If the pool has only one adapter, it will be cleared.
Parameters
| The new adapter to set, or null to set no adapter. |
See Also
- swapAdapter(Adapter, boolean)
public void?setChildDrawingOrderCallback?(RecyclerView.ChildDrawingOrderCallback?childDrawingOrderCallback)
Sets the?RecyclerView.ChildDrawingOrderCallback?to be used for drawing children.
See?getChildDrawingOrder(int, int)?for details. Calling this method will always call?setChildrenDrawingOrderEnabled(boolean). The parameter will be true if childDrawingOrderCallback is not null, false otherwise.
Note that child drawing order may be overridden by View's elevation.
Parameters
| The ChildDrawingOrderCallback to be used by the drawing system. |
public void?setClipToPadding?(boolean clipToPadding)
Sets whether this ViewGroup will clip its children to its padding and resize (but not clip) any EdgeEffect to the padded region, if padding is present.
By default, children are clipped to the padding of their parent ViewGroup. This clipping behavior is only enabled if padding is non-zero.
Parameters
| true to clip children to the padding of the group, and resize (but not clip) any EdgeEffect to the padded region. False otherwise. |
public void?setHasFixedSize?(boolean hasFixedSize)
RecyclerView can perform several optimizations if it can know in advance that changes in adapter content cannot change the size of the RecyclerView itself. If your use of RecyclerView falls into this category, set this to true.
Parameters
| true if adapter changes cannot affect the size of the RecyclerView. |
public void?setItemAnimator?(RecyclerView.ItemAnimator?animator)
Sets the?RecyclerView.ItemAnimator?that will handle animations involving changes to the items in this RecyclerView. By default, RecyclerView instantiates and uses an instance of?DefaultItemAnimator. Whether item animations are enabled for the RecyclerView depends on the ItemAnimator and whether the LayoutManager?supports item animations.
Parameters
| The ItemAnimator being set. If null, no animations will occur when changes occur to the items in this RecyclerView. |
public void?setItemViewCacheSize?(int size)
Set the number of offscreen views to retain before adding them to the potentially shared?recycled view pool.
The offscreen view cache stays aware of changes in the attached adapter, allowing a LayoutManager to reuse those views unmodified without needing to return to the adapter to rebind them.
Parameters
| Number of views to cache offscreen before returning them to the general recycled view pool |
public void?setLayoutFrozen?(boolean frozen)
Enable or disable layout and scroll. After?setLayoutFrozen(true)?is called, Layout requests will be postponed until?setLayoutFrozen(false)?is called; child views are not updated when RecyclerView is frozen,?smoothScrollBy(int, int),?scrollBy(int, int),?scrollToPosition(int)?and?smoothScrollToPosition(int)are dropped; TouchEvents and GenericMotionEvents are dropped;?onFocusSearchFailed(View, int, Recycler, State)?will not be called.
setLayoutFrozen(true)?does not prevent app from directly calling?scrollToPosition(int),?smoothScrollToPosition(RecyclerView, State, int).
setAdapter(Adapter)?and?swapAdapter(Adapter, boolean)?will automatically stop frozen.
Note: Running ItemAnimator is not stopped automatically, it's caller's responsibility to call ItemAnimator.end().
Parameters
| true to freeze layout and scroll, false to re-enable. |
public void?setLayoutManager?(RecyclerView.LayoutManager?layout)
Set the?RecyclerView.LayoutManager?that this RecyclerView will use.
In contrast to other adapter-backed views such as?ListView?or?GridView, RecyclerView allows client code to provide custom layout arrangements for child views. These arrangements are controlled by the?RecyclerView.LayoutManager. A LayoutManager must be provided for RecyclerView to function.
Several default strategies are provided for common uses such as lists and grids.
Parameters
| LayoutManager to use |
public void?setNestedScrollingEnabled?(boolean enabled)
Enable or disable nested scrolling for this view.
If this property is set to true the view will be permitted to initiate nested scrolling operations with a compatible parent view in the current hierarchy. If this view does not implement nested scrolling this will have no effect. Disabling nested scrolling while a nested scroll is in progress has the effect of?stopping?the nested scroll.
Parameters
| true to enable nested scrolling, false to disable |
public void?setOnScrollListener?(RecyclerView.OnScrollListener?listener)
This method is deprecated.
Use?addOnScrollListener(OnScrollListener)?and?removeOnScrollListener(OnScrollListener)
Set a listener that will be notified of any changes in scroll state or position.
Parameters
| Listener to set or null to clear |
public void?setRecycledViewPool?(RecyclerView.RecycledViewPool?pool)
Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. This can be useful if you have multiple RecyclerViews with adapters that use the same view types, for example if you have several data sets with the same kinds of item views displayed by a?ViewPager.
Parameters
| Pool to set. If this parameter is null a new pool will be created and used. |
public void?setRecyclerListener?(RecyclerView.RecyclerListener?listener)
Register a listener that will be notified whenever a child view is recycled.
This listener will be called when a LayoutManager or the RecyclerView decides that a child view is no longer needed. If an application associates expensive or heavyweight data with item views, this may be a good place to release or free those resources.
Parameters
| Listener to register, or null to clear |
public void?setScrollingTouchSlop?(int slopConstant)
Configure the scrolling touch slop for a specific use case. Set up the RecyclerView's scrolling motion threshold based on common usages. Valid arguments areTOUCH_SLOP_DEFAULT?and?TOUCH_SLOP_PAGING.
Parameters
| One of the?TOUCH_SLOP_?constants representing the intended usage of this RecyclerView |
public void?setViewCacheExtension?(RecyclerView.ViewCacheExtension?extension)
Sets a new?RecyclerView.ViewCacheExtension?to be used by the Recycler.
Parameters
| ViewCacheExtension to be used or null if you want to clear the existing one. |
See Also
- ERROR(ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)} /{@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)})
public void?smoothScrollBy?(int dx, int dy)
Animate a scroll by the given amount of pixels along either axis.
Parameters
| Pixels to scroll horizontally |
| Pixels to scroll vertically |
public void?smoothScrollToPosition?(int position)
Starts a smooth scroll to an adapter position.
To support smooth scrolling, you must override?smoothScrollToPosition(RecyclerView, State, int)?and create a?RecyclerView.SmoothScroller.
RecyclerView.LayoutManager?is responsible for creating the actual scroll action. If you want to provide a custom smooth scroll logic, overridesmoothScrollToPosition(RecyclerView, State, int)?in your LayoutManager.
Parameters
| The adapter position to scroll to |
See Also
- smoothScrollToPosition(RecyclerView, State, int)
public boolean?startNestedScroll?(int axes)
Begin a nestable scroll operation along the given axes.
A view starting a nested scroll promises to abide by the following contract:
The view will call startNestedScroll upon initiating a scroll operation. In the case of a touch scroll this corresponds to the initial?ACTION_DOWN. In the case of touch scrolling the nested scroll will be terminated automatically in the same manner as?requestDisallowInterceptTouchEvent(boolean). In the event of programmatic scrolling the caller must explicitly call?stopNestedScroll()?to indicate the end of the nested scroll.
If?startNestedScroll?returns true, a cooperative parent was found. If it returns false the caller may ignore the rest of this contract until the next scroll. Calling startNestedScroll while a nested scroll is already in progress will return true.
At each incremental step of the scroll the caller should invoke?dispatchNestedPreScroll?once it has calculated the requested scrolling delta. If it returns true the nested scrolling parent at least partially consumed the scroll and the caller should adjust the amount it scrolls by.
After applying the remainder of the scroll delta the caller should invoke?dispatchNestedScroll, passing both the delta consumed and the delta unconsumed. A nested scrolling parent may treat these values differently. See?onNestedScroll(View, int, int, int, int).
Parameters
| Flags consisting of a combination of?SCROLL_AXIS_HORIZONTAL?and/or?SCROLL_AXIS_VERTICAL. |
Returns
- true if a cooperative parent was found and nested scrolling has been enabled for the current gesture.
public void?stopNestedScroll?()
Stop a nested scroll in progress.
Calling this method when a nested scroll is not currently in progress is harmless.
public void?stopScroll?()
Stop any current scroll in progress, such as one started by?smoothScrollBy(int, int),?fling(int, int)?or a touch-initiated fling.
public void?swapAdapter?(Adapter?adapter, boolean removeAndRecycleExistingViews)
Swaps the current adapter with the provided one. It is similar to?setAdapter(Adapter)?but assumes existing adapter and the new adapter uses the sameRecyclerView.ViewHolder?and does not clear the RecycledViewPool.
Note that it still calls onAdapterChanged callbacks.
Parameters
| The new adapter to set, or null to set no adapter. |
| If set to true, RecyclerView will recycle all existing Views. If adapters have stable ids and/or you want to animate the disappearing views, you may prefer to set this to false. |
See Also
- setAdapter(Adapter)
Protected Methods
protected boolean?checkLayoutParams?(ViewGroup.LayoutParams?p)
protected void?dispatchRestoreInstanceState?(SparseArray<Parcelable> container)
Override to prevent thawing of any views created by the adapter.
Parameters
| The SparseArray which holds previously saved state. |
protected void?dispatchSaveInstanceState?(SparseArray<Parcelable> container)
Override to prevent freezing of any views created by the adapter.
Parameters
| The SparseArray in which to save the view's state. |
protected?ViewGroup.LayoutParams?generateDefaultLayoutParams?()
Returns a set of default layout parameters. These parameters are requested when the View passed to?addView(View)?has no layout parameters already set. If null is returned, an exception is thrown from addView.
Returns
- a set of default layout parameters or null
protected?ViewGroup.LayoutParams?generateLayoutParams?(ViewGroup.LayoutParams?p)
Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test ofcheckLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.
Parameters
| The layout parameters to convert into a suitable set of layout parameters for this ViewGroup. |
Returns
- an instance of?ViewGroup.LayoutParams?or one of its descendants
protected int?getChildDrawingOrder?(int childCount, int i)
Returns the index of the child to draw for this iteration. Override this if you want to change the drawing order of children. By default, it returns i.
NOTE: In order for this method to be called, you must enable child ordering first by calling?setChildrenDrawingOrderEnabled(boolean).
Parameters
| The current iteration. |
Returns
- The index of the child to draw this iteration.
protected void?onAttachedToWindow?()
This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called beforeonDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after?onMeasure(int, int).
protected void?onDetachedFromWindow?()
This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
protected void?onLayout?(boolean changed, int l, int t, int r, int b)
Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.
Parameters
| This is a new size or position for this view |
| Left position, relative to parent |
| Top position, relative to parent |
| Right position, relative to parent |
| Bottom position, relative to parent |
protected void?onMeasure?(int widthSpec, int heightSpec)
Measure the view and its content to determine the measured width and the measured height. This method is invoked by?measure(int, int)?and should be overridden by subclasses to provide accurate and efficient measurement of their contents.
CONTRACT:?When overriding this method, you?must?call?setMeasuredDimension(int, int)?to store the measured width and height of this view. Failure to do so will trigger an?IllegalStateException, thrown by?measure(int, int). Calling the superclass'?onMeasure(int, int)?is a valid use.
The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should overrideonMeasure(int, int)?to provide better measurements of their content.
If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight()?and?getSuggestedMinimumWidth()).
Parameters
| horizontal space requirements as imposed by the parent. The requirements are encoded with?View.MeasureSpec. |
| vertical space requirements as imposed by the parent. The requirements are encoded with?View.MeasureSpec. |
protected void?onRestoreInstanceState?(Parcelable?state)
Hook allowing a view to re-apply a representation of its internal state that had previously been generated by?onSaveInstanceState(). This function will never be called with a null state.
Parameters
| The frozen state that had previously been returned by?onSaveInstanceState(). |
protected?Parcelable?onSaveInstanceState?()
Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.
Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.
Returns
- Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.
protected void?onSizeChanged?(int w, int h, int oldw, int oldh)
This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.
Parameters
| Current width of this view. |
| Current height of this view. |
| Old width of this view. |
| Old height of this view. |
protected void?removeDetachedView?(View?child, boolean animate)
Finishes the removal of a detached view. This method will dispatch the detached from window event and notify the hierarchy change listener.
This method is intended to be lightweight and makes no assumptions about whether the parent or child should be redrawn. Proper use of this method will include also making any appropriate?requestLayout()?or?invalidate()?calls. For example, callers can?post?a?Runnable?which performs a?requestLayout()?on the next frame, after all detach/remove calls are finished, causing layout to be run prior to redrawing the view hierarchy.
Parameters
| the child to be definitely removed from the view hierarchy |
| if true and the view has an animation, the view is placed in the disappearing views list, otherwise, it is detached from the window |
.
總結
以上是生活随笔為你收集整理的【Android应用开发】RecycleView API 翻译 (文档翻译)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Studio NDK 代
- 下一篇: 【Android 应用开发】 Andro