RecyclerView使用SnapHelper輔助類控制滑動對齊方式
SnapHelper是RecyclerView的輔助類,用于控制在滑動結(jié)束后,RecyclerView中item的對齊方式。SnapHelper是一個抽象類,系統(tǒng)內(nèi)置了兩個默認(rèn)實現(xiàn)類:LinearSnapHelper和PagerSnapHelper。
LinearSnapHelper使當(dāng)前Item居中顯示,常用場景是橫向的RecyclerView,類似ViewPager效果,但是又可以快速滑動(滑動多頁)。而PagerSnapHelper的展示效果和LineSnapHelper是一樣的,只是PagerSnapHelper限制一次只能滑動一頁,不能快速滑動。
SnapHelper通過處理RecyclerView的fling,來達(dá)到要展示的效果。使用SnapHelper時,需要將其綁定到RecyclerView控件上。可以通過計算對齊RecyclerView中TargetView的指定點或者容器中的任何像素點,使RecyclerView實現(xiàn)類似于ViewPager的切換效果。
LinearSnapHelper效果:
PagerSnapHelper效果:
SnapHelper使用
- 創(chuàng)建SnapHelper對象:可以使用LinearSnapHelper或PagerSnapHelper創(chuàng)建SnapHelper對象。
- 綁定到RecyclerView:創(chuàng)建SnapHelper對象后,需要將其綁定到對應(yīng)的RecyclerView對象上。調(diào)用SnapHelper對象的attachToRecyclerView()方法即可將SnapHelper綁定到RecyclerView控件上。
- 實現(xiàn)Fling操作:SnapHelper通過處理RecyclerView的fling操作來達(dá)到要展示的效果。當(dāng)手指在屏幕上滑動RecyclerView然后松手時,RecyclerView中的內(nèi)容會順著慣性繼續(xù)往手指滑動的方向繼續(xù)滾動直到停止,這個過程叫做Fling。需要實現(xiàn)RecyclerView.LayoutManager接口,并實現(xiàn)其onFling方法來處理Fling操作。
- 監(jiān)聽Fling事件:SnapHelper監(jiān)聽RecyclerView.OnFlingListener中的onFling接口,當(dāng)發(fā)生Fling事件時,會觸發(fā)相應(yīng)的回調(diào)函數(shù)。可以在回調(diào)函數(shù)中處理SnapHelper的邏輯,例如根據(jù)當(dāng)前的滾動位置對item進(jìn)行對齊操作。
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)
//或
val snapHelper = PagerSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)