[英]Release resources in PagerAdapter
I have a PagerAdapter, and in instantiateItem
i initialize an ExoPlayer
.我有一个 PagerAdapter,并在instantiateItem
中初始化一个ExoPlayer
。
My question is, how do I release the player?我的问题是,如何释放播放器?
I assume, somehow the function destroyItem
should be involved, but destroyItem
only gehts the view as an object.我认为,应该以某种方式涉及 function destroyItem
,但destroyItem
仅将视图视为 object。 How can I release resources specific to this one item of the PagerAdapter
?如何释放特定于PagerAdapter
的这一项目的资源?
Here my source, if someone is interested:这是我的来源,如果有人感兴趣:
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)
}
You don't need to return a View
from the method instantiateItem()
, you can also return a wrapper containing your ExoPlayer
and your View
.您不需要从方法instantiateItem()
返回View
,您还可以返回包含ExoPlayer
和View
的包装器。
eg例如
data class Wrapper(val view: View, val player: ExoPlayer)
And in your PagerAdapter
:在您的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()
}
If you want instead to return a view from instantiateItem()
you can assign the ExoPlayer
as the tag of the view to retrieve it later.如果您想从instantiateItem()
返回一个视图,您可以将ExoPlayer
指定为视图的标签,以便稍后检索它。
eg例如
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.