【问题标题】:how to access exoplayer methods inside recycler view adapter如何访问回收器视图适配器中的 exoplayer 方法
【发布时间】:2020-06-17 11:35:34
【问题描述】:

我有一个播放视频的 exoplayer。我想捕捉它的当前位置。

所以,在 MainActivity 中

lateinit var player: SimpleExoPlayer

fun timeCapture(view: View) {
        Log.d(TAG,"${player.currentPosition}")
    }

工作正常

但是,事实上需要在 Recycler 视图适配器上捕获这个事件

在 MainActivity 我像这样将数据传递给回收站视图,

 var viewAdapter = MainActivityAdapter(data)

由于player 是lateinit 我无法在如下适配器中访问它

        Log.d("logger","${MainActivity().player.currentPosition}")

这会出错。

所以,对此有任何建议

【问题讨论】:

  • 你想在什么时候捕捉这个事件?任何事件,如点击项目
  • 您可以将 ExoPlayer 的实例传递给您的适配器 MainActivityAdapter(data,exoplayer)。然后用它在适配器类中做任何你想做的事情。
  • @AlphaOne 我这样做了,但是我正在初始化用户选择视频的 exoplayer。因此,在 oncreate exoplayer 中没有初始化。
  • @naanu 好的。做一件事,创建一个全局变量和函数以在适配器类中设置该变量。当用户选择像 setPlayer(exoplayer) 这样的视频时调用该函数
  • @AlphaOne 你的意思是单例变量。那怎么办?

标签: java android kotlin exoplayer exoplayer2.x


【解决方案1】:

您只需要创建一个全局变量即可。并且在使用它时要小心处理错误。

GlobalVariables.kt

package com.company.notexist.model

import com.google.android.exoplayer2.SimpleExoPlayer

object GlobalVariables {
    lateinit var player: SimpleExoPlayer
}

要访问以上player 变量,请将其导入任何文件

import com.company.notexist.model.GlobalVariables.player

then rest of the code is normal
...
player = ExoPlayerFactory.newSimpleInstance(this)
id_player_view.player = player
...
...

然后在适配器上像这样使用它,

Log.d("logger","${player.currentPosition}")

但不要忘记导入语句和错误处理(即检查 null 和其他内容)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多