如何访问我的 recyclerAdapter 中的共享 viewModel

2024-01-03

我的 viewModel 包含一些变量,例如应在 recyclerView 中创建多少个 cardView。因此,我正在寻找一种方法来访问适配器类中的相同 viewModel 对象。有没有办法或更好的选择?我的代码是 kotlin 语言

class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
    private val gameViewModel: GameViewModel by activityViewModels()

由于您只提供了 2 行代码,因此很难确切地知道您做错了什么。

通常,您会在 Activity 类或 Fragment 类中检索 ViewModel,如下所示

class MyActivity /* other stuff */ {
    // this line produces/retrieves an instance of GameViewModel
    // where its owner is MyActivity
    private val gameViewModel: GameViewModel by viewModels()
}

然后在活动类中的其他地方实例化 RecycleAdapter 类。在那里你可以将 gameViewModel 传递给它。当然,为了能够做到这一点,您的 RecyclerAdapter 要么必须接受 GameViewModel 作为构造函数参数,要么通过 setter 或其他一些函数调用。

这是通过构造函数参数的示例。您的 RecyclerAdapter 类必须定义如下(请注意,这是用于声明属性并从主构造函数初始化它们的 Kotlin 简洁语法 https://kotlinlang.org/docs/classes.html#constructors)

class RecyclerAdapter(
    private val gameViewModel: GameViewModel,
    // add more constructor parameters/class properties here if needed
) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
    // other class properties that you don't want to initialize
    // through the primary constructor
    // ...

    // the class body where you implement RecyclerView.Adapter<> methods
    // ...
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // gameViewModel can be used here
        gameViewModel.doSomething()
    }
}

最后一步,修改代码中创建 RecyclerAdapter 实例的行

    // here we create a new RecyclerAdapter and pass the gameViewModel to it
    val adapter = RecyclerAdapter(gameViewModel)
    recyclerView.adapter = adapter
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何访问我的 recyclerAdapter 中的共享 viewModel 的相关文章

随机推荐