片段内的VideoView,滑动时如何停止播放视频?

时间:2018-08-11 19:46:57

标签: android android-fragments android-lifecycle

我有一个viewPager,可同时显示图像和视频。 但是,当用户播放视频 并立即滑动到下一个片段时,上一个视频将继续播放!

这是我播放视频的方式

videoView!!.setVideoURI(uri)
videoView!!.setMediaController(MediaController(context))
videoView!!.requestFocus()

play.setOnClickListener(View.OnClickListener {
    if (!videoView!!.isPlaying()) {
    videoView!!.start()
    videoView!!.setVisibility(View.VISIBLE)
}

我尝试插入

if (videoView!!.isPlaying()) {
     videoView!!.setMediaController(null)
     videoView?.stopPlayback()
}

在viewPager片段的 onStop onPause onDetach 中,但是它不起作用。

您的帮助将非常宝贵!

2 个答案:

答案 0 :(得分:1)

一个简单的界面:

interface Playable {

    fun play()

    fun stop()
}

包含VideoView的片段必须实现此接口

class VideoFragment : Fragment(), Playable {
...
    override fun play() {
        //play logic
    }

    override fun stop() {
        //stop logic
    }
...
}

PagerAdapter:

class PagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm){

    private val instantiatedItems = SparseArrayCompat<WeakReference<Any>>()
    private var selectedPosition: Int by Delegates.observable(-1) { _, oldPosition, newPosition ->
        fun playableAt(position: Int) = instantiatedItems.get(position)?.get() as? Playable
        playableAt(oldPosition)?.stop()
        playableAt(newPosition)?.play()
    }
...
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        return super.instantiateItem(container, position).also {
            instantiatedItems.put(position, WeakReference(it))
        }
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        instantiatedItems.remove(position)
        super.destroyItem(container, position, `object`)
    }

    fun onPageSelected(position: Int) {
        selectedPosition = position
    }
}

最后:

...
pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                adapter.onPageSelected(position)//this method is declared in PagerAdapter
            }
        }.also {
            pager.post { it.onPageSelected(pager.currentItem) }
        })
...

答案 1 :(得分:0)

您可以申请

if (videoView!!.isPlaying()) { videoView!!.setMediaController(null) videoView?.stopPlayback() ; 

pager.addOnPageChangeListener();中。