Ami Hollander
Ami Hollander

Reputation: 2545

Handle touch listeners in ViewPager with an inner fragment within a fragment

I'm using a ViewPager with an FragmentStatePagerAdapter in order to show a list of fragments Group A, thats allows me to swipe between fragments by touch. Each fragment from Group A holds an inner fragment Group B.

In one of the fragments from Group B, there is a Chart object which enables a horizontal scrolling which intercepts with the touch listeners.

I couldn't figure how to avoid the Group A scorlling (The ViewPager swipe) when the user tries to scroll the data in the Chart object.

enter image description here

As it shown in the picture:

Any suggestions? Thank you.

Upvotes: 0

Views: 845

Answers (1)

savepopulation
savepopulation

Reputation: 11921

You can disable swipe ability of your view pager when user touches your charts and give it back when user stops touching your chart. First define a Non-Swipable ViewPager and make your view pager NonSwipable.

public class NonSwipableViewPager extends ViewPager {
    private boolean canScroll = true;
    public NonSwipableViewPager(Context context) {
        super(context);
    }
    public NonSwipableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public void setCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return canScroll && super.onTouchEvent(ev);
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return canScroll && super.onInterceptTouchEvent(ev);
    }

    public boolean isCanScroll() {
        return canScroll;
    }
}

Keep it in a public variable. (Keeping it with a public variable in activity may not be de best practice.)

Add a touch listener to your chart and disable swipe ability of your view pager like below:

            View yourChart = (YourChart) view.findViewById(R.id.your_chart);
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (activity.mainViewPager != null) {
                            activity.mainViewPager.setCanScroll(false);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        if (activity.mainViewPager != null) {
                            activity.mainViewPager.setCanScroll(true);
                        }
                        break;
                }
                return false;
            }
        });

Upvotes: 2

Related Questions