RecyclerView中提供的方法解析
它提供了scrollTo(),scrollBy(),scrollToPosition(),smoothScrollBy(),smoothScrollToPosition()方法,下面将详细解释这些方法的作用。
?
1 2 3 |
public void scrollTo( int x, int y) {
Log.w( "RecyclerView" , "RecyclerView does not support scrolling to an absolute position. Use scrollToPosition instead" ); } |
该方法在View中的意思是滑动到绝对位置,比如当前位置为(10,10),通过scrollTo(30,30),最后的位置为(30,30)。但从上面scrollTo方法源代码中可以看出,RecyclerView并不支持滑动到绝对位置,因为该方法为空实现,而是使用scrollToPosition(position)方法来代替。
?
1 2 3 4 5 6 7 8 9 10 11 12 |
public void scrollBy( int x, int y) {
if ( this .mLayout == null ) {
Log.e( "RecyclerView" , "Cannot scroll without a LayoutManager set. Call setLayoutManager with a non-null argument." ); } else if (! this .mLayoutFrozen) {
boolean canScrollHorizontal = this .mLayout.canScrollHorizontally(); boolean canScrollVertical = this .mLayout.canScrollVertically(); if (canScrollHorizontal || canScrollVertical) {
this .scrollByInternal(canScrollHorizontal?x: 0 , canScrollVertical?y: 0 , (MotionEvent) null ); } } } |
该方法为滑动到相对位置,比如当前位置为(10,10),通过scrollBy(30,30),最后的位置为(40,40)。在该方法中,首先会判断mLayout是否为空,mLayout就是RecyclerView持有的LayoutManager,然后再判断RecyclerView是横向还是垂直滑动,如果是横向滑动则取(x,0)传递到scrollByInternal方法中,反之垂直则取(0,y)。
?
1 2 3 4 5 6 7 8 9 10 11 |
public void scrollToPosition( int position) {
if (! this .mLayoutFrozen) {
this .stopScroll(); if ( this .mLayout == null ) {
Log.e( "RecyclerView" , "Cannot scroll to position a LayoutManager set. Call setLayoutManager with a non-null argument." ); } else {
this .mLayout.scrollToPosition(position); this .awakenScrollBars(); } } } |
该方法为滑动到RecyclerView中的指定位置(滑动过程中没有动画),由上面代码可以看出,实际上是委托给了LayoutManager的scrollToPosition方法,在LinearLayoutManager的scrollToPosition方法为:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public void smoothScrollBy( int dx, int dy) {
this .smoothScrollBy(dx, dy, (Interpolator) null ); } public void smoothScrollBy( int dx, int dy, Interpolator interpolator) {
if ( this .mLayout == null ) {
Log.e( "RecyclerView" , "Cannot smooth scroll without a LayoutManager set. Call setLayoutManager with a non-null argument." ); } else if (! this .mLayoutFrozen) {
if (! this .mLayout.canScrollHorizontally()) {
dx = 0 ; } if (! this .mLayout.canScrollVertically()) {
dy = 0 ; } if (dx != 0 || dy != 0 ) {
this .mViewFlinger.smoothScrollBy(dx, dy, interpolator); } } } |
这个两个方法都是平滑滑动到相对位置。smoothScrollBy(int dx, int dy)方法间接调用的smoothScrollBy(int dx, int dy, Interpolator interpolator)方法,参数interpolator为插值器,它是一个接口,和动画使用的插值器一样。