I have a layout design that looks like the drawing below. When I move the viewpager2 below, I want the top viewpager2 to move synchronously. the solutions i found on the internet didn't work
myViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Log.e("Selected_Page", String.valueOf(position));
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
CodePudding user response:
You didn't explain your issues very well. But if am to guess, maybe you're trying to scroll top view2pager upwards when scrolling the bottom view2pager too.
If this is what you want, then you can nest both of them in a NestedscrollView and give nestedScrollingChild to true in NestedScrollView so that onScroll can be intercepted on each children.
Note: NestedScrollView can only take one direct child e.g LinearLayout . So put the 2 view2pagers inside a View group or layout
CodePudding user response:
It's not 100% synchronously, pixel-wise. But an easy and clean solution, which also looks very sleek (imho) could be the following:
pagerBottom.registerOnPageChangeCallback(object : OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
pagerTop.setCurrentItem(position, true)
}
})
Here, a listener is added to the bottom ViewPager2
. When a page change is detected, a smooth scroll is done on the top ViewPager2
. Only works, if both pagers have the same amount of pages, of course.