標籤:移動 blank strong div 滑動 his replace roi tle
如何擷取 RecyclerView 的滑動距離?
RecyclerView 雖然有getScrollX() 和 getScrollY(), 但是測試發現這兩個函數總是返回0,太無語了。因此想到了下面幾種方法來實現擷取滑動距離:
1. 利用OnScrollListener
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { private int totalDy = 0; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { totalDy -= dy; } });
如代碼所述,totalDy的確儲存了 RecyclerView 的滑動距離,但是當我向下滑動 RecyclerView ,之後插入/刪除/移動 Item 的時候,totalDy 就變得不精確了;比如刪除或者插入新的Item,那麼totalDy就不能再迴歸到 0了。
解決辦法:監聽RecyclerView的addOnScrollListener後自己記錄onScrolled的dy,同時給adapter加個registerAdapterDataObserver,監聽插入/刪除/移動,自己加減前面記錄的dy滾動值。自己沒有試過,不知道是否可行!
2. 有人說可以嘗試computeVerticalScrollOffset()
totalDy = recyclerView.computeVerticalScrollOffset();
然而compute方法計算出的並不是滑動的精確距離,stackOverflow上有答案解釋其為 item 的平均高度 * 可見 item 數目,不是我們需要的精確距離。
3. 還有人說可以嘗試getChildAt(0)
totalDy = recyclerView.getChildAt(0).getTop();
依靠第一個item的滑動距離來進行動畫的設定,但是根據該方法得出的 totalDy 在滑動到一定程度後清零。
這是因為recyclerViewl.getChildAt(0) 返回的永遠是第一個可見的child,不是所有view list 的第一個child,因此這種用法是得不到滑動距離的。
另外下面這三種用法都是等價的,都是擷取第一個可見的child:
LinearLayoutManager layoutManager = (LinearLayoutManager) this.getLayoutManager(); View firstVisiableChildView = this.getChildAt(0); View firstVisiableChildView = layoutManager.getChildAt(0) int position = layoutManager.findFirstVisibleItemPosition(); View firstVisiableChildView = layoutManager.getChildAt(position)
但是下面這種就不是擷取第一個可見的child,而是獲得所有view list 的第一個child。但是滑動一段距離後它總是返回null,即第一個child被recycle後,總是返回null。
//Don‘t use this function to get the first item, it will return null when the first item is recycled. LinearLayoutManager layoutManager = (LinearLayoutManager) this.getLayoutManager();View child2 = layoutManager.findViewByPosition(0);
4.如果LayoutManager用的是LinearLayoutManager,強烈推薦下面的方法擷取滑動距離:
public int getScollYDistance() { LinearLayoutManager layoutManager = (LinearLayoutManager) this.getLayoutManager(); int position = layoutManager.findFirstVisibleItemPosition(); View firstVisiableChildView = layoutManager.findViewByPosition(position); int itemHeight = firstVisiableChildView.getHeight(); return (position) * itemHeight - firstVisiableChildView.getTop(); }
Android 如何擷取Android RecyclerView滑動的距離