在我的程序中,我有一个带有适配器的RecyclerView,我在其中检查单击了RecyclerView的哪个元素。
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentBreakfast = breakfastList[position]
holder.breakfastTitle.text = context.getText(currentBreakfast.breakfastStringResourceId)
holder.breakfastImage.setImageResource(currentBreakfast.breakfastImageResourceId)
holder.breakfastImage.setOnClickListener {
holder.itemView.findNavController().navigate(R.id.action_breakfastFragment_to_DetailsFragment)
showDetails(currentBreakfast)
}
}
我想将有关特定单击元素的数据(如imageId、stringId、Name等)传递给另一个片段DetailsFragment,我想在其中显示更多数据
我该怎么做呢?
2条答案
按热度按时间ff29svar1#
你需要把你的片段发送到你调用的适配器,我猜它是breakfastFragment,只要把
this
加到它上面:您的适配器将获得
fragment
:你可以使用
fragment
来导航它:在另一个片段中获取该值,并在日志中查看它们,如下所示:
我只是编造了一些变量名和类名,因为你没有分享它们,只是用你正确的名字来改变它。
wsewodh22#
有几种方法。
我建议你看一下这个答案(公认答案):How to pass data from adapter to fragment?
然后转到名为“更多的Kotlin方法是忽略接口,只传递一个函数”的部分。
这是我自己也在使用的方法。
下面是如何定义RecyclerView的适配器的示例:
然后,您需要将回调函数附加到Viewholder中的click侦听器-在我的示例中,它看起来像这样(列表中的每个项目都有一个cardview -在xml文件中定义):
然后,在传递给RecylerView Adapter的回调函数中,您可以导航到包含相关数据的details片段--我的一个回调函数(在创建时传递给Adapter)看起来如下所示(在“拥有”RecylerView的Fragment中定义):
(here使用我的导航图创建用于NavController的Action)
我的适配器很容易用一些数据和对回调函数的引用进行初始化: