ViewPager having different size Fragments
Currently i am working on a app named ‘ReweyouFoums’. I was trying to implement the UI as shown below.

Here i thought to use viewpager for three fragments, Explore Groups, Main Feeds, Your Groups in the respective order with main feeds fragment as the default start page.

I easily implemented the same but now a new issue occurred. You might notice that there is a toolbar with some action buttons. Now whenever i clicked them they didn’t work or the viewpager consumed the click itself.

I actually wanted to keep MainFeed fragment below the toolbar and simultaneously the ExploreGroups, YourGroups fragments on top of it. So that i could get a overlapping effect when i swipe the MainFeeds fragment, as shown above.
For this i provided a top padding of toolbar height to the ‘MainFeeds’ fragment. Also i kept z-order of ViewPager higher than AppBarLayout in xml (otherwise toolbar would always overlap the viewpager).
Now after doing this, it's the time to make those action buttons clickable.
For that i built CustomViewPager and override its dispatchTouchEvent() (you could also use onInterceptTouchEvent()):
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (ev.getY() < Utils.convertpxFromDp(48) && pageposition ==
POSTION_MAIN_FEED) {
return false;
} else return super.dispatchTouchEvent(ev);
}
return super.dispatchTouchEvent(ev);
}Here i am checking, if my current page is MainFeed fragment, also the Y-coordinate of user touch is on the toolbar(ie within 48dp , the toolbar size in my case).If yes, then i should prevent touch events to be used by Viewpager, and hence the touch event gets passed to toolbar below it and clicks on action items starts working.
To keep the track of current page in viewpager i used this piece of code below in the CustomViewPager class itself:
addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
pageposition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});I hope you now got an idea of how to work with different sizes fragments inside ViewPager and also preventing the touch event glitches.
Share your feedback ☎ and recommend this article ❤️ to your friends.
Thanks!
The above code is implemented in my app named “ReweyouForums”. Do check it out once.
https://play.google.com/store/apps/details?id=in.reweyou.reweyouforums
