How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1305
心在旅途
心在旅途 2020-11-22 00:24

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

For example, I have 2 fragments with

26条回答
  •  有刺的猬
    2020-11-22 00:54

    I overrode the Count method of the associated FragmentStatePagerAdapter and have it return the total count minus the number of pages to hide:

     public class MyAdapter : Android.Support.V13.App.FragmentStatePagerAdapter
     {   
         private List _fragments;
    
         public int TrimmedPages { get; set; }
    
         public MyAdapter(Android.App.FragmentManager fm) : base(fm) { }
    
         public MyAdapter(Android.App.FragmentManager fm, List fragments) : base(fm)
         {
             _fragments = fragments;
    
             TrimmedPages = 0;
         }
    
         public override int Count
         {
             //get { return _fragments.Count; }
             get { return _fragments.Count - TrimmedPages; }
         }
     }
    

    So, if there are 3 fragments initially added to the ViewPager, and only the first 2 should be shown until some condition is met, override the page count by setting TrimmedPages to 1 and it should only show the first two pages.

    This works good for pages on the end, but wont really help for ones on the beginning or middle (though there are plenty of ways of doing this).

提交回复
热议问题