ListView停止滚动

Android中,如果想停止ListView中的滑动,我们可以通过下面的方法来实现,主要是通过反射父类AbsListView的调用endFling方法来实现。

ListView源码

通过AbsListView的源码,我们可以知道,是通过下面的方法来停止其滑动的,那我们就可以通过使用java的反射来在适当的时候调用此方法。

void More ...endFling() {
    mTouchMode = TOUCH_MODE_REST;

    removeCallbacks(this);
    removeCallbacks(mCheckFlywheel);

    reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
    clearScrollingCache();//清除cache,要以将scrollingCache和animateCache设置为false
    mScroller.abortAnimation();

    if (mFlingStrictSpan != null) {
        mFlingStrictSpan.finish();
        mFlingStrictSpan = null;
    }
}

看源码,它里面也有很多地方,调用此方法,比如下面的平稳滑动方法smoothScrollBy:

void More ...smoothScrollBy(int distance, int duration, boolean linear) {
if (mFlingRunnable == null) {
    mFlingRunnable = new FlingRunnable();
}

// No sense starting to scroll if we're not going anywhere
final int firstPos = mFirstPosition;
final int childCount = getChildCount();
final int lastPos = firstPos + childCount;
final int topLimit = getPaddingTop();
final int bottomLimit = getHeight() - getPaddingBottom();

if (distance == 0 || mItemCount == 0 || childCount == 0 ||
        (firstPos == 0 && getChildAt(0).getTop() == topLimit && distance < 0) ||
        (lastPos == mItemCount &&
                getChildAt(childCount - 1).getBottom() == bottomLimit && distance > 0)) {
    mFlingRunnable.endFling();//停止滑动
    if (mPositionScroller != null) {
        mPositionScroller.stop();
    }
} else {
    reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
    mFlingRunnable.startScroll(distance, duration, linear);
}
}

完整调用示例:

public class MyListView extends ListView{

        public MyListView(Context context) {
            super(context);
        }

        /**
         * 停止滑动
         */
        public void stopScroll() {
            try {
                Field flingEndField = AbsListView.class.getDeclaredField("mFlingRunnable" );
                flingEndField.setAccessible(true);
                Method flingEndMethod = flingEndField .getType().getDeclaredMethod("endFling");
                flingEndMethod.setAccessible(true);
                flingEndMethod.invoke(flingEndField.get(this));
            } catch (Exception e) {
            }
        }
    }
文章目录
|