从ViewHolder获取适配器实例 [英] Getting an adapter instance from a ViewHolder
问题描述
我正在尝试创建一个上下文浮动菜单,其中包含所选菜单的信息(位置,id等),以便可以在我的Fragment中的覆盖方法 onContextItemSelected
中访问.
I'm trying to create a contextual floating menu with the information (position,id,etc) of the selected menu to be accessible inside the overridden method onContextItemSelected
in my Fragment.
所以我有一个从 RecyclerView.Adapter< ViewHolder>
扩展的自定义适配器,以及一个自定义的 ViewHolder
类在单独的文件中.我注册了我的点击监听器,并在自定义 ViewHolder
类中提供了其处理程序.
So I have a custom adapter extending from RecyclerView.Adapter<ViewHolder>
and a custom ViewHolder
class in separate file.
I registered my click listener and provided its handler inside the custom ViewHolder
class.
由于在事件触发时我需要将 ViewHolder
信息发送回我的片段,所以我需要对我的适配器进行引用,因为我的片段具有 adapter对象引用代码>,但没有
viewholder对象引用
.因此,在自定义 ViewHolder
的实例化阶段(因为没有方法从 ViewHolder
类获取适配器引用),我将适配器引用传递给自定义的构造函数ViewHolder
在其处理程序中使用,因此我可以在 ViewHolder
类内调用此引用,以将信息从 ViewHolder
传递给 Adapter
,最后从 Adapter
到 Fragment
.
Since I need to send the ViewHolder
information back to my Fragment when the event is fired, I need to have a reference to my Adapter because my fragment has the adapter object reference
but not viewholder object reference
. So in instantiation stage of the custom ViewHolder
(because there is no method to get Adapter reference from ViewHolder
class), I pass the adapter reference to constructor of the custom ViewHolder
for the use in its handler so I can call this reference inside the ViewHolder
class to pass the information to Adapter
from ViewHolder
, and finally from Adapter
to Fragment
.
我的问题是,是否仍将处理程序保留在 ViewHolder
中,这是一种更好的做法还是一种通用方法?就我而言,我注意到每个ViewHolder实例都必须保留对适配器的引用,这会消耗内存.按照我上面列出的方式进行操作,将来可能会发生任何冲突吗?
My question is, is there a better practice or a general approach by still keeping the handler inside the ViewHolder
? In my case, I notice every ViewHolder instance will have to keep a reference to adapter, which consumes memory. Is there any conflict that may arise in the future by doing it the way I listed above?
推荐答案
也许我不太了解您的模式,但是您正在寻找的参考已经存在.
Maybe I'm not understanding well your pattern, but the reference you are looking for, it is already there.
fragmens知道适配器引用,而适配器知道您的视口.使用 getAdapterPosition()来获取对您的对象的引用
The fragmens knows the adapter reference, and the adapter knows your viewholder. Use getAdapterPosition() to get that reference to your Object
假设在您的 RecyclerView.Adapter< ViewHolder>
中有一个名为 list 的 ArrayList< String>
:例如,该代码显示了片段中的Toast,其中包含单击的String的值
Suppose to have a ArrayList<String>
named list in your RecyclerView.Adapter<ViewHolder>
: this code, for example, shows a Toast in the Fragment with the value of the clicked String
public ViewHolder( View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String myValue = list.get( getAdapterPosition() ); // your object
Toast.makeText(activity, myValue, Toast.LENGTH_SHORT).show();
}
});
}
这篇关于从ViewHolder获取适配器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!