Scroll a ListView by pixels in Android

后端 未结 5 1433
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 08:50

I want to scroll the a ListView in Android by number of pixels. For example I want to scroll the list 10 pixels down (so that the first item on the list has its top

5条回答
  •  春和景丽
    2021-02-06 09:51

    If you look at the source for the scrollListBy() method added in api 19 you will see that you can use the package scoped trackMotionScroll method.

    public class FutureListView {
    
        private final ListView mView;
    
        public FutureListView(ListView view) {
            mView = view;
        }
    
        /**
         * Scrolls the list items within the view by a specified number of pixels.
         *
         * @param y the amount of pixels to scroll by vertically
         */
        public void scrollListBy(int y) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mView.scrollListBy(y);
            } else {
                // scrollListBy just calls trackMotionScroll
                trackMotionScroll(-y, -y);
            }
        }
    
        private void trackMotionScroll(int deltaY, int incrementalDeltaY) {
            try {
                Method method = AbsListView.class.getDeclaredMethod("trackMotionScroll", int.class, int.class);
                method.setAccessible(true);
                method.invoke(mView, deltaY, incrementalDeltaY);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            };
        }
    }
    

提交回复
热议问题