How to know viewpager is scroll left or right?

前端 未结 13 1960
梦谈多话
梦谈多话 2020-12-13 06:18

I am using ViewPager (support library). I want to know every time the ViewPager change the visible page, it is scrolling left or right.

Please give me a solution. An

13条回答
  •  旧时难觅i
    2020-12-13 07:12

    Apologies - had to edit the answer as I found a bug. Here is improved solution:

    The solution compares current page index with one previously selected (previousPageIndex)

    newPageIndex represents the page which is about to be scrolled to.

    Condition (positionOffset == 0) compares if the scroll finished

    private int previousPageIndex = 0;
    private int newPageIndex = -1;
    
    private final int MOVE_DIRECTION_NONE = 0;
    private final int MOVE_DIRECTION_LEFT = 1;
    private final int MOVE_DIRECTION_RIGHT = 2;
    
    private int moveDirection = MOVE_DIRECTION_NONE;
    
    
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels);
    
        if (moveDirection == MOVE_DIRECTION_NONE) {
            if (previousPageIndex  == position){
                moveDirection = MOVE_DIRECTION_LEFT;
                if (newPageIndex == -1) newPageIndex = previousPageIndex + 1;
            }  else {
                moveDirection = MOVE_DIRECTION_RIGHT;
                if (newPageIndex == -1) newPageIndex = previousPageIndex - 1;
            }
        }
    
        if (positionOffset == 0) {
            System.out.println("Reseting");
            previousPageIndex = position;
            moveDirection = MOVE_DIRECTION_NONE;
            newPageIndex = -1;
        }
    
        switch (moveDirection) {
            case MOVE_DIRECTION_LEFT:
                if (onPageChangingHandler != null) onPageChangingHandler.pageChanging(previousPageIndex, newPageIndex, positionOffset);
                System.out.println("Sliding Left | Previous index: " + previousPageIndex + " | New Index: " + newPageIndex + " | offset: " + positionOffset  + " | Position: " + position);
                break;
            case MOVE_DIRECTION_RIGHT:
                if (onPageChangingHandler != null) onPageChangingHandler.pageChanging(newPageIndex, previousPageIndex, positionOffset);
                System.out.println("Sliding Right | Previous index: " + previousPageIndex + " | New Index: " + newPageIndex + " | offset: " + positionOffset + " | Position: " + position);
                break;
            case MOVE_DIRECTION_NONE:
                System.out.println("Moving NONE");
                break;
        }
    }
    

提交回复
热议问题