Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- val context: Context,
- @LayoutRes val layoutRes: Int,
- val medias: List<MediaFiles> = listOf()
- ) : PagerAdapter() {
- private var player: SimpleExoPlayer? = null
- override fun isViewFromObject(view: View, o: Any): Boolean {
- return view == o
- }
- override fun getCount() = medias.size
- override fun instantiateItem(container: ViewGroup, position: Int): Any {
- return LayoutInflater.from(context).inflate(layoutRes, container, false).apply {
- if (medias.isNotEmpty()) {
- when (medias[position].mediaType) {
- MediaType.PHOTO -> {
- // Display the Image
- }
- MediaType.VIDEO -> {
- ssImageView.makeInvisible(true)
- exoPlayerView.makeVisible()
- player = ExoPlayerFactory.newSimpleInstance(
- DefaultRenderersFactory(context),
- DefaultTrackSelector(),
- DefaultLoadControl()
- )
- if (medias[position].uri != null)
- initPlayer(this, medias[position].uri!!)
- }
- null -> {
- }
- }
- }
- container.addView(this, 0)
- }
- }
- private fun initPlayer(view: View, uri: Uri) {
- Timber.i("initPlayer: uri: $uri")
- with(view) {
- player!!.let {
- exoPlayerView.player = it
- it.prepare(buildMediaSource(uri), true, false)
- it.playWhenReady = false
- }
- }
- }
- private fun buildMediaSource(uri: Uri) = ExtractorMediaSource.Factory(
- DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getString(R.string.app_name)))
- )
- .setExtractorsFactory(DefaultExtractorsFactory())
- .createMediaSource(uri)
- override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
- releasePlayer()
- }
- private fun releasePlayer() {
- if (player != null) {
- playWhenReady = false
- player!!.release()
- player = null
- }
- }
- }```
- Setting the adapter to the ViewPager.
- ```val mediaAdapter = MediaVPAdapter(
- this,
- R.layout.fragment_media,
- true,
- medias?.toList() ?: listOf()
- )
- vpMedia.adapter = mediaAdapter
- vpMedia.currentItem = position ?: 0
- vpMedia.offscreenPageLimit = 1```
- If I click on a Video, the selected Video could be played but when I scroll to some other item, none of them were playing. When I try to toggle the Play/Pause button, only the button was toggling.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement