Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. val context: Context,
  2. @LayoutRes val layoutRes: Int,
  3. val medias: List<MediaFiles> = listOf()
  4. ) : PagerAdapter() {
  5.  
  6. private var player: SimpleExoPlayer? = null
  7.  
  8. override fun isViewFromObject(view: View, o: Any): Boolean {
  9. return view == o
  10. }
  11.  
  12. override fun getCount() = medias.size
  13.  
  14. override fun instantiateItem(container: ViewGroup, position: Int): Any {
  15. return LayoutInflater.from(context).inflate(layoutRes, container, false).apply {
  16. if (medias.isNotEmpty()) {
  17. when (medias[position].mediaType) {
  18. MediaType.PHOTO -> {
  19. // Display the Image
  20. }
  21. MediaType.VIDEO -> {
  22.  
  23. ssImageView.makeInvisible(true)
  24. exoPlayerView.makeVisible()
  25. player = ExoPlayerFactory.newSimpleInstance(
  26. DefaultRenderersFactory(context),
  27. DefaultTrackSelector(),
  28. DefaultLoadControl()
  29. )
  30. if (medias[position].uri != null)
  31. initPlayer(this, medias[position].uri!!)
  32.  
  33. }
  34. null -> {
  35.  
  36. }
  37. }
  38. }
  39.  
  40. container.addView(this, 0)
  41. }
  42. }
  43.  
  44. private fun initPlayer(view: View, uri: Uri) {
  45. Timber.i("initPlayer: uri: $uri")
  46. with(view) {
  47. player!!.let {
  48. exoPlayerView.player = it
  49.  
  50. it.prepare(buildMediaSource(uri), true, false)
  51.  
  52. it.playWhenReady = false
  53. }
  54. }
  55. }
  56.  
  57. private fun buildMediaSource(uri: Uri) = ExtractorMediaSource.Factory(
  58. DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getString(R.string.app_name)))
  59. )
  60. .setExtractorsFactory(DefaultExtractorsFactory())
  61. .createMediaSource(uri)
  62.  
  63.  
  64. override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
  65. releasePlayer()
  66. }
  67.  
  68. private fun releasePlayer() {
  69. if (player != null) {
  70. playWhenReady = false
  71. player!!.release()
  72. player = null
  73. }
  74. }
  75. }```
  76.  
  77. Setting the adapter to the ViewPager.
  78. ```val mediaAdapter = MediaVPAdapter(
  79. this,
  80. R.layout.fragment_media,
  81. true,
  82. medias?.toList() ?: listOf()
  83. )
  84. vpMedia.adapter = mediaAdapter
  85. vpMedia.currentItem = position ?: 0
  86. vpMedia.offscreenPageLimit = 1```
  87.  
  88. 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