VideoView on Viewpager, stopping video when switching page

I solved this by overriding the method:

void setUserVisibleHint(boolean isVisibleToUser)

Don't know if that's the proper way though.


You have to override setUserVisibleHint method in a fragment where u play video.

   public void setUserVisibleHint(boolean isVisibleToUser) 
   {       
    super.setUserVisibleHint(isVisibleToUser);                         
     if (this.isVisible())
     {               
        if (!isVisibleToUser)   // If we are becoming invisible, then...
        {  
          //pause or stop video
        }

        if (isVisibleToUser) // If we are becoming visible, then...
        {                               
            //play your video               
        }
    } 
  }

Most likely your mAdapter.getItem is creating a new fragment each time. This will cause the video view to always be null.

public class MyAdapter extends FragmentStatePagerAdapter {
    SparseArray<Fragment>fragments = new SparseArray<Fragment>();
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return contents.size();
    }

    @Override
    public Fragment getItem(int position) {
        Fragment frag = fragments.get(position);
        Bundle args = new Bundle();
        if(frag != null){
            return frag;
        }
        fragments.put(position, frag);
        return frag;
    }
}