Issue in swiping views in ViewPager

1.3k views Asked by At

My View Pager consists of photos,audios and videos.Audio View consists of play button to play the audio.When i click on play button it disappears and audio start playing.When I stop the audio or when track is completed play button again becomes visible. If i swipe the view while audio is being played and move to next view then the audio stops.But the issue is if I move to next view by swiping while the audio is being played and then return to the audio view then i can't see the play button on View Pager.However if i swipe to next to next view or to further next views and then return to the audio view then i can see the play button on Audio View.Same happens for back also.If I move to previous view by swiping from audio view while audio is being played and then return to the audio view the i can't see the play button on View Pager.However if i swipe to previous to previous view or to further previous views and then return to the audio view then i can see the play button on View Pager..

2

There are 2 answers

3
Phillip Dunley On BEST ANSWER

The reason is that when the fragment 0 is active, then Android also initiates the adjacent fragments, in this case only 1. When you swipe to fragment 1, since fragment 0 is already initiated, android only initiates fragment 2. This is the reason when you move back from fragment 1 to fragment 0, you do not see the play button.

Now when you move to fragment 2 and then back to fragment 1, fragment 0 will get refreshed, hence you can see the button again.

Honestly, I have struggled with the same problem. This has been discussed in StackOverflow multiple times. I found the following post to be most useful.

Update data in ListFragment as part of ViewPager

0
android developer On

What you are describing is just the way the ViewPager works.

At any moment, the only pages it holds is the current one, one on the left and one on the right. When you scroll, pages can be destroyed according to where you are.

In any case, if you wish to handle switching between pages, you can simply add a listener to the ViewPager, by using setOnPageChangeListener .

This way, you can identify which page was selected before, and which one is selected now.

If you wish, you can post a project and I will see what I can do to fix it.

I also suggest to use fragments instead of views for a bit easier handling of each page's lifecycle. In addition, if you wish to save the state of the page, you can use FragmentStatePagerAdapter .