Skip to content Skip to sidebar Skip to footer

How To Prevent Parent Viewpager From Scrolling When The Child Viewpager Is At The Last Item?

I have a nested ViewPager that works brilliantly. The only issue is, once the child ViewPager is at the last item and I scroll further, the parent ViewPager scrolls. I do not want

Solution 1:

First create a CustomViewPager to change it's swipeable state like below:

publicclassCustomViewPagerextendsViewPager {
    privateboolean canScroll = true;
    publicCustomViewPager(Context context) {
        super(context);
    }
    publicCustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    publicvoidsetCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
    }
    @OverridepublicbooleanonTouchEvent(MotionEvent ev) {
        return canScroll && super.onTouchEvent(ev);
    }
    @OverridepublicbooleanonInterceptTouchEvent(MotionEvent ev) {
        return canScroll && super.onInterceptTouchEvent(ev);
    }

    publicbooleanisCanScroll() {
        return canScroll;
    }
}

Second change your view pager which you want to disable it's swipe propery to your CustomViewPager

Get your view pagers:

CustomViewPagermyCustomViewPager= (CustomViewPager) findViewById(R.id.my_custom_pager);
ViewPagerviewPager= (ViewPager) findViewById(R.id.view_pager);

Add an onTouchListener to your ViewPager:

viewPager.setOnTouchListener(newView.OnTouchListener() {
            @OverridepublicbooleanonTouch(View v, MotionEvent event) {
                switch (event.getAction())
                {
                    caseMotionEvent.ACTION_DOWN:
                        myCustomViewPager.setCanScroll(false);
                        break;

                    caseMotionEvent.ACTION_UP:
                        myCustomViewPager.setCanScroll(true);
                        break;
                }
                returnfalse;
            }
        });

If you really need to check if your viewpager's current position:

intpos=0;
    viewPager.addOnPageChangeListener(newViewPager.OnPageChangeListener() {
                @OverridepublicvoidonPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @OverridepublicvoidonPageSelected(int position) {
                   pos = position;
                }

                @OverridepublicvoidonPageScrollStateChanged(int state) {

                }
            });

And you can chek in your MotionEvents if pos == yourAdaptersItemCount-1 and disable or enable your customViewPager.

Good luck.

Post a Comment for "How To Prevent Parent Viewpager From Scrolling When The Child Viewpager Is At The Last Item?"