访问 Recycler's Adapter 中的 ViewModel

visit ViewModel in Recycler´s Adapter

我遇到了一个问题,我想在 RecyclerView 的适配器中访问我的 ViewModel,但我遇到了异常: “您的 activity 尚未附加到 Application 实例。您不能在调用 onCreate 之前请求 ViewModel”

class FoodInSortAdapter( val activity:MainActivity,private val list:List<String>):RecyclerView.Adapter<FoodInSortAdapter.Holder>() {

    val viewModel :FoodViewModel by lazy {
        println("servus")
        ViewModelProvider(activity).get(FoodViewModel::class.java)}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.sortitem, parent, false)
        return Holder(view)
    }


    override fun onBindViewHolder(holder: Holder, position: Int) {
        holder.sortName.text = list[position]
        holder.itemView.setOnClickListener {
            val m=list[position]
            viewModel.setQuery(m)
        }
    }

有人知道怎么了吗?

谢谢

首先,您不应在 activity 或片段之外初始化 viewModel。

我假设您没有在 onCreate 中而是在初始化阶段创建适配器。有两种解决方案供您参考。

  1. 在activity中初始化vm,并通过新添加的方法setupViewModel在适配器中设置它,在onCreate中调用。那个比较好
class FooActivity : Activity{

  private val viewModel: FoodViewModel by lazy {
        println("servus")
        ViewModelProvider(activity).get(FoodViewModel::class.java)
  }

  private val adapter = FoodInSortAdapter(emptyList())

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        adapter.setupViewModel(viewModel)
  }

}

class FoodInSortAdapter(private val list:List<String>):RecyclerView.Adapter<FoodInSortAdapter.Holder>() {

    private lateinit var viewModel: FoodViewModel

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.sortitem, parent, false)
        return Holder(view)
    }


    override fun onBindViewHolder(holder: Holder, position: Int) {
        holder.sortName.text = list[position]
        holder.itemView.setOnClickListener {
            val m=list[position]
            viewModel.setQuery(m)
        }
    }

   fun setupViewModel(vm: FoodViewModel){
      viewModel = vm
   }
}
  1. onCreate 方法中创建适配器,这应该也适用于您。

干杯