Navigation Using ViewPager2 Without Fragments

Nathan Sokalski 4,116 Reputation points
2023-01-08T03:20:40.76+00:00

I am attempting to use a ViewPager2 to allow the user to navigate between screens by swiping. Each screen is an XML Layout that is included using an include tag for which I set the visibility. I know how to use ViewPager2 for collections, but I simply want to set the visibility of a screen (a View, usually a GridLayout) to gone or visible (or possibly some additional miscellaneous actions) when the user swipes. I do not want to recycle or regenerate any items, because I am not navigating through a collection, I just want to be notified when the user swipes. However, because ViewPager2 is based on RecyclerView, it forces me to use RecyclerView.Adapter and create a RecyclerView.ViewHolder. All navigation examples I could find attempt to use Fragments. How can I simply be notified when the user swipes?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,293 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,491 Reputation points Microsoft Vendor
    2023-01-12T01:15:03.4633333+00:00

    Hello,

    If you want to detect the scroll event in ViewPager2, you can RegisterOnPageChangeCallbackin the ViewPager2 with viewpager2.RegisterOnPageChangeCallback(new MyViewPagerChange());, then override the OnPageSelectedand OnPageScrolled like following code.

    internal class MyViewPagerChange : ViewPager2.OnPageChangeCallback    {        
    		public override void OnPageSelected(int position){            
    				base.OnPageSelected(position);        
            }        
             public override void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)                           {            
                    base.OnPageScrolled(position, positionOffset, positionOffsetPixels);        
            }    
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments