Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VideoView on Viewpager, stopping video when switching page

I have a viewpager with different fragments, one of these has a videoview in it. If I switch page when the video is playing then it remaings playing even when I'm on a different page. I tried implementing an OnPageChangeListener for the ViewPager like this:

viewpager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {

                if(position!=mAdapter.getCount()-1){
                    MultimediaFragment frag = (MultimediaFragment)mAdapter.getItem(position+1);
                    frag.onPageIsChanged();
                }

                if(position != 0){
                    MultimediaFragment frag = (MultimediaFragment)mAdapter.getItem(position-1);
                    frag.onPageIsChanged();
                }


            }

With onPageIsChanged() being a method of my own which tries to tell my videoview attribute to stop and hide controls:

public void onPageIsChanged() {
        if(mVideoView!=null){
            if(mVideoView.isPlaying()){
                mVideoView.stopPlayback();
            }
            mMedia.hide();
        }
    }

The problem is that mVideoView is always null, even when it's playing on the background. This videoview is created on the OnCreateView method of the fragment, but shouldn't it remain set to my mVideoView field until fragment is destroyed?

like image 368
MichelReap Avatar asked Feb 13 '13 12:02

MichelReap


2 Answers

I solved this by overriding the method:

void setUserVisibleHint(boolean isVisibleToUser)

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

like image 174
Gabriel Sanmartin Avatar answered Oct 01 '22 00:10

Gabriel Sanmartin


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               
        }
    } 
  }
like image 27
Manish Butola Avatar answered Oct 01 '22 02:10

Manish Butola