停止ListView滚动动画

whl*_*hlk 3 android listview scroll android-listview

我有ListView大约100个条目.当用户从下到上进行"甩动"时,即使手指不再触摸显示器,它也会开始滚动并继续滚动.

有没有办法在此时停止滚动动画?

小智 16

然后我们查找android源代码(AbsListView),给它一个ACTION_CANCEL touchEvent,可以停止fling.这很容易.

listView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0, 0, 0));
Run Code Online (Sandbox Code Playgroud)


Kni*_*edi 9

我没有尝试解决方案,Pompe de velo但因为smoothScrollToPosition()不适用于低于8的API级别,这对我没有用.

我同意,改变默认行为不是一个好主意,但有时你需要.所以这是我的(脏)解决方案,它使用反射.这是迄今为止不推荐的方式,因为它是一个黑客但它适用于我.可能有更好的解决方案,但我没有找到它.

class StopListFling {

    private static Field mFlingEndField = null;
    private static Method mFlingEndMethod = null;

    static {
        try {
            mFlingEndField = AbsListView.class.getDeclaredField("mFlingRunnable");
            mFlingEndField.setAccessible(true);
            mFlingEndMethod = mFlingEndField.getType().getDeclaredMethod("endFling");
            mFlingEndMethod.setAccessible(true);
        } catch (Exception e) {
            mFlingEndMethod = null;
        }
    }

    public static void stop(ListView list) {
        if (mFlingEndMethod != null) {
            try {
                mFlingEndMethod.invoke(mFlingEndField.get(list));
            } catch (Exception e) {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)