Tuesday, January 31, 2017

ViewPager update fragment on swipe – Android

1) Attach the Listener:
 mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {  
       @Override  
       public void onPageScrolled(final int i, final float v, final int i2) {  
       }  
       @Override  
       public void onPageSelected(final int i) {  
         YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, i);  
         if (fragment != null) {  
           fragment.fragmentBecameVisible();  
         }   
       }  
       @Override  
       public void onPageScrollStateChanged(final int i) {  
       }  
     });  
2) This is your Interface:
 public interface YourFragmentInterface {  
   void fragmentBecameVisible();  
 }  
3) Change your fragments so they implement this:
 public class YourLovelyFragment extends Fragment implements YourFragmentInterface {  
4) Implement the interface in the fragment
 @Override  
 public void fragmentBecameVisible() {  
   // You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.  
 }  

No comments :

Post a Comment