Canberk Ozcelik
Canberk Ozcelik

Reputation: 641

Viewpager scrolling left on first item

Is it possible to detect if ViewPager's first item is being tried to scrolled left?
I'm trying to achieve an experience like on Instagram stories that the view closes on scrolling left on the first item.

I can hold and fill a pair list inside ViewPager.OnPageChangeListener interface's onPageScrolled method and check if position 0 scrolled by 0.0 repeated N times, close the view but it sounds redundant.

Any other pieces of advice? Thanks in advance.

private int currentPagePosition = 0;
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageScrolled(int i, float v, int i1) {
        // TODO Hold pair list and fill with i and v values
        Log.d("ViewPager", "onPageScrolled from " + i + " by " + v);
    }

    @Override
    public void onPageSelected(int selectedPagePosition) {
        Log.d("ViewPager", "onPageSelected pos: " + selectedPagePosition);
        if (currentPagePosition != selectedPagePosition) {
            // do something
        }
        currentPagePosition = selectedPagePosition;
    }

    @Override
    public void onPageScrollStateChanged(int i) {
        switch (i) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (currentPagePosition == 0) {
                    // TODO if pair list contains N times repeated 0 to 0.0 items close the view
                }
                Log.d("ViewPager", "onPageScrollStateChanged IDLE on " + currentPagePosition);
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:
                Log.d("ViewPager", "onPageScrollStateChanged DRAGGING from " + currentPagePosition);
                break;
        }
    }
};

Upvotes: 0

Views: 376

Answers (1)

Marian Paździoch
Marian Paździoch

Reputation: 9093

I think you want to use the PageTransformer which will give you the position with - or + depending on which direction the page is dragged. You just have to detect the CHANGE in sign of that value.

Upvotes: 1

Related Questions