0

I've implemented Dave Smith's elegant solution to displaying multiple views inside a ViewPager here, but am having trouble dispatching touch events to the fragments that are not the "focused" one.

In his PagerContainer solution, there is functionality to handle the touch events outside of the ViewPager's focused area (see below), but that's only to enable scrolling. I need those touch events to actually interact with the views on the fragments themselves.

Does anyone have any experience with this?

@Override
public boolean onTouchEvent(MotionEvent ev) {
    //We capture any touches not already handled by the ViewPager
    // to implement scrolling from a touch outside the pager bounds.
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mInitialTouch.x = (int)ev.getX();
            mInitialTouch.y = (int)ev.getY();
        default:
            ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
            break;
    }

    return mPager.dispatchTouchEvent(ev);
}

How do I get the touch events from the PagerContainer propagated to the appropriate fragment?

Community
  • 1
  • 1
airowe
  • 794
  • 2
  • 9
  • 29

3 Answers3

0

You can use Event bus for this purpose checkout this link how to use it.I have used it for this kind of communications between activities and fragments. https://github.com/greenrobot/EventBus

Learner_Programmer
  • 1,259
  • 1
  • 13
  • 38
0

So, I've got a partial solution implemented but it's not the final answer. In the OnTouchEvent overridden in the PagerContainer, I'm now checking the HitRect of each fragment and determining what fragment the event's point is inside. The problem now? How to stop scrolling to the fragment that's been selected.

Here's what I've tried, but it's still scrolling to the clicked on fragment. Any ideas on how to stop this?

@Override
public boolean onTouchEvent(MotionEvent evt) {

    //We capture any touches not already handled by the ViewPager
    // to implement scrolling from a touch outside the pager bounds.
    int fragCount = mPager.getAdapter().getCount();
    for(int i = 0; i < fragCount; i++)
    {
        View view = mPager.getChildAt(i);
        Rect rect = new Rect();
        view.getHitRect(rect);

        if(rect.contains((int)evt.getX(),(int)evt.getY()))
        {
            int currentItem = mPager.getCurrentItem();
            if(currentItem != i)
            {
                mPager.clearOnPageChangeListeners();
                mPager.setCurrentItem(currentItem + i, false);
                mPager.addOnPageChangeListener(this);
            }
            break;
        }
    }

    return mPager.dispatchTouchEvent(evt);
}
airowe
  • 794
  • 2
  • 9
  • 29
0

If anyone stumbles on this question and is looking for a solution, I ended up using HorizontalGridView instead of ViewPager...

Javadoc for HorizontalGridView here

HorizontalGridView Sample

airowe
  • 794
  • 2
  • 9
  • 29