Kotlin - 如何在 RecyclerView 中传递 TextToSpeech 的上下文参数?

Kotlin - How to pass in the Context parameter for TextToSpeech within a RecyclerView?

在学习教程时,“this”用于上下文,但是弹出的错误是“Context! was expected”。我也尝试了 getActivity() ,它给出了一个未解决的引用。我尝试的第三个选项是 Activity,它给出了错误,“分类器 'Activity' 没有伴随对象,因此必须在此处初始化”

current code

目标是让 TextToSpeech 在回收器适配器中工作。我遇到的主要问题是在 TextToSpeech class.

中为上下文参数传递什么

“tts = TextToSpeech(this, this )”通常在教程中给出,这在 fragment/recyclerView.

中不起作用

假设您在 onBindViewHolder() 中,您可以利用 View 的所有实例都有一个 context 属性:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val context = holder.itemView.context
    // now you can use context anywhere below
}

或者,您可以在 RecyclerViews onCreateViewHolder 中从 MainActivity 或 Fragment 传递上下文

//declare context var
private lateinit var context:Context

 @NonNull
    override fun onCreateViewHolder(@NonNull parent: ViewGroup, viewType: Int): MyViewHolder {
       ...
        context = parent.context
     ...,
    }