【问题标题】:Context Unresolved Reference上下文未解决的参考
【发布时间】:2019-05-08 06:59:32
【问题描述】:

我正在设置我的 RecyclerView 的适配器, 我需要使用 Activity Context 来填充我的 viewmodel 变量,稍后我将使用它来移动意图。为什么我得到未解决的参考,即使我把我的上下文放在课堂上?

自从of() 方法要求FragmentActivity 以来,我已经尝试强制转换为FragmentActivity,但还是一样。

class TodoAdapter constructor(x:ArrayList<Notes>, c: Context) : RecyclerView.Adapter<TodoAdapter.Handler>() {
    private var lists:ArrayList<Notes> = x
    private var context:Context = c
    private lateinit var viewmodel:TodoViewModel

    class Handler(private val itemBinding:NotesListBinding): RecyclerView.ViewHolder(itemBinding.root) {
        fun bind(note:Notes){
            itemBinding.dataclass = note
            itemBinding.viewmodel = ViewModelProviders.of(context).get(TodoViewModel::class.java)
            itemBinding.notesCardView.setCardBackgroundColor(note.color)
        }
    }

我希望上下文会被很好地引用,因为它在同一个类中。但它返回如下错误:

e: /media/cua/Projectah/Android Studio/TODOLisT/app/src/main/java/com/cua/todolist/adapter/recyclerviewadapter/TodoAdapter.kt: (24, 59): Unresolved reference: context

【问题讨论】:

    标签: android mvvm kotlin android-recyclerview


    【解决方案1】:

    context 变量未解析,因为Handler 没有对TodoAdapter 的引用。为此,您必须将其声明为inner class Handler。虽然你不应该这样做!

    改为提供viewmodelbind

    fun bind(note: Notes, viewmodel: TodoViewModel) {
        itemBinding.dataclass = note
        itemBinding.viewmodel = viewmodel
        itemBinding.notesCardView.setCardBackgroundColor(note.color)
    }
    

    还可以考虑在数据绑定中设置卡片背景颜色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 2020-04-18
      • 1970-01-01
      • 2023-01-25
      • 2019-04-05
      • 1970-01-01
      • 2021-08-17
      • 2016-12-14
      相关资源
      最近更新 更多