I implemented the new ViewPager for my project. The viewPager2 contains a list of fragment
private class ViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Integer> classifiedIds;
ViewPagerAdapter(@NonNull Fragment fragment, final ArrayList<Integer> classifiedIds) {
super(fragment);
this.classifiedIds = classifiedIds;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return DetailsFragment.newInstance(classifiedIds.get(position));
}
@Override
public int getItemCount() {
return classifiedIds.size();
}
}
Inside the fragment I got an horizontal recyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerViewPicture.setLayoutManager(layoutManager);
The issue is when I try to scroll the recyclerview the viewPager take the touch and swap to the next fragment
When I was using the old ViewPager I didn't have this issue
I find a solution it's a know bug as you can see here https://issuetracker.google.com/issues/123006042 maybe they would solve it in the next updates
Thanks to TakeInfos and the exemple project inside the link
recyclerViewPicture.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
int lastX = 0;
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) e.getX();
break;
case MotionEvent.ACTION_MOVE:
boolean isScrollingRight = e.getX() < lastX;
if ((isScrollingRight && ((LinearLayoutManager) recyclerViewPicture.getLayoutManager()).findLastCompletelyVisibleItemPosition() == recyclerViewPicture.getAdapter().getItemCount() - 1) ||
(!isScrollingRight && ((LinearLayoutManager) recyclerViewPicture.getLayoutManager()).findFirstCompletelyVisibleItemPosition() == 0)) {
viewPager.setUserInputEnabled(true);
} else {
viewPager.setUserInputEnabled(false);
}
break;
case MotionEvent.ACTION_UP:
lastX = 0;
viewPager.setUserInputEnabled(true);
break;
}
return false;
}
@Override
public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
I'm checking if the user scroll on the right or on the left. If the user reach the end or the start of the recyclerView I'm enable or disable the swipe on the view pager