I am using View Pager with fragment to showing image and video, I am able to show image and video properly but I have problem, when I swipe for video, then video is playing,
It is because ViewPager
keeps offscreen fragments started. For instance you have a fragment visible to the user. ViewPager
will try to keep the previous fragment (on the left side) and the next fragment (on the right side) started. This allows ViewPager
performing smooth sliding when user decides to change the page, because the next and the previous pages are already prepared.
In your case the video player is not visible (offscreen), but ViewPager
keeps it started as due to the behaviour described above. You can use setOffscreenPageLimit() method to change this behaviour. If you set page limit to 0
, then offscreen fragments will be paused immediately. Unfortunately they will not only be paused, but stopped and detached from the activity too. This means when you return back to your fragment, it will recreate the whole layout anew. That's why you can try to override either Fragment.setUserVisibleHint()
or Fragment.onHiddenChanged()
and execute your pause/play logic there. ViewPager
will update hidden state of a fragment depending on whether the fragment is actually visible to user or not.
Hope this helps.
I handle the problem like this:
boolean isVisible = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
isVisible = isVisibleToUser;
if(player!=null)
player.pause();
super.setUserVisibleHint(isVisibleToUser);
}
then in onCreateView method:
SimpleExoPlayer player;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
PlayerView playerView = v.findViewById(R.id.playerView);
playerView.getLayoutParams().width = ListPager.widthPixels;
playerView.getLayoutParams().height = ListPager.widthPixels;
if(player!=null)
player.release();
player = new SimpleExoPlayer.Builder(App.applicationContext).build();
playerView.setPlayer(player);
MediaItem mediaItem = MediaItem.fromUri(url);
player.setMediaItem(mediaItem);
player.prepare();
//---------The following code is important because if you remove the following if
// then if the next page is displaying, android will automatically initiate the
// previous and the next page, and the player will start playing :|
if(isVisible)
player.play();
}
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)
{
//play your video
}
}
}