Kotlin - 通过片段传递参数

Posted

技术标签:

【中文标题】Kotlin - 通过片段传递参数【英文标题】:Kotlin - Passing args through Fragments 【发布时间】:2020-11-03 18:23:11 【问题描述】:

我的应用有问题。它有 3 个片段(F1 + F2 + F3)

在 F1 中(收到一个包含 x 个运动的列表),用户应该选择一个(RecyclerView 用于呈现数据)。 在 F2 上(接收设备列表),用户应该选择设备(也使用 RecyclerView) 在 F3 中,我想恢复用户的选择。我尝试使用 ShareViewModel,但每次尝试使用它时,它在 F3 中显示为 null。

传递此参数的最佳方法是什么??! SharedViewModel 你在使用 SafeArgs 吗?!我尝试使用SharedViewModel

请注意,以下代码并非从 android studio 复制而来,可能包含一些执行错误。

   override fun onBindViewHolder(holder: ViewHolder, position: Int) 
        holder.itemview.text=listsports[position]

        holder.itemview.setOnClickListener
    
        val sViewModel=SharedViewModel()
    
        sViewModel.setSport(adapterposition)
    
        v:View->v.findNavcontroller().navigate(R.id.action_F1_to_F2)
    

ShareViewModel 就像:

class SharedViewModel():ViewModel()

var selectSport= MutableLiveData<String>
val _selectSports=LiveData<String>
get()=selectSport


fun setSport(index:Int)

    selectSport.value=listsports[position].toString()



【问题讨论】:

【参考方案1】:

而不是使用:

val sViewModel=SharedViewModel()

尝试使用:

val sViewModel: SharedViewModel by activityViewModels()

在你的每一个片段中

cf:文档https://developer.android.com/topic/libraries/architecture/viewmodel

【讨论】:

问题是我试图将值传递给 RecyclerViewClass 中的 ShareViewModel。它显示 未解决的参考:activityViewModels 我猜你的意思是在适配器内部?如果是这样,您可以在 recyclerview 的构造函数中传递片段

以上是关于Kotlin - 通过片段传递参数的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin - 通过 Intent 将函数作为参数传递

测试是否调用通过函数参数传递的函数(Android / Kotlin))

通过适配器在片段之间传递数据(Kotlin Android)

在 Kotlin 中将接口作为参数传递

操作栏选项卡:使用多次实例化的单个片段时如何传递参数

如何将参数从 Flutter 传递给 Kotlin?