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