我有一个PagerAdapter,并在instantiateItem
中初始化了一个ExoPlayer
。
我的问题是,如何释放播放器?
[我认为,某种程度上应该包含函数destroyItem
,但是destroyItem
仅将视图作为对象。如何释放PagerAdapter
这一项目的专用资源?
如果有人对此感兴趣,请点击这里。
override fun instantiateItem(container: ViewGroup, position: Int): Any {
[...]
url.contains(mContext.getString(R.string.video_file_indicator)) -> {
val exoPlayer = ExoPlayerFactory.newSimpleInstance(mContext)
videoView.player = exoPlayer
val dataSourceFactory : DataSource.Factory = DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, mContext.getString(R.string.app_name)))
var videoSource : MediaSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(url))
if (url == Helper.getUserProfile().profileVideoUrl) {
val localFile = File(mContext.getExternalFilesDir(null), Helper.profilePicVideoName)
videoSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(localFile.toUri())
}
exoPlayer.prepare(videoSource)
exoPlayer.playWhenReady = true
exoPlayer.repeatMode = Player.REPEAT_MODE_ONE
videoView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
}
}
container.addView(layout)
return layout
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
您不需要从方法View
返回instantiateItem()
,也可以返回包含ExoPlayer
和View
的包装器。
例如
data class Wrapper(val view: View, val player: ExoPlayer)
以及您的PagerAdapter
:
override fun instantiateItem(container: ViewGroup, position: Int): Any {
[...]
return Wrapper(layout, exoPlayer)
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val wrapper = `object` as Wrapper
container.removeView(wrapper.view)
// Release the player here.
wrapper.player.doSomething()
}
如果要改为从instantiateItem()
返回视图,则可以将ExoPlayer
分配为视图的标签,以便以后检索。
例如
override fun instantiateItem(container: ViewGroup, position: Int): Any {
[...]
return layout.apply {
setTag(exoPlayer)
}
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val view = `object` as View
container.removeView(view)
// Release the player here.
val exoPlayer = view.getTag() as ExoPlayer
exoPlayer.doSomething()
}