如何将一个适配器之间的数据发送到另一个适配器?



>实际上,我有一个回收器视图,其中有一个按钮和(我在其中获得带有位置的id[来自RestAPi调用](--->>当单击按钮时,我设置了另一个回收器视图。现在我想从第一个回收器视图适配器。我已经尝试过全局变量

这是图像 在此处输入图像描述

根据我之前对另一个问题的回答,我认为您需要一个Singleton Pattern而不是全局变量

您只需要一个返回另一个Adapter'sArrayList<SingleItemModel>getter,但您将面临的问题是您需要从Activity中具有相同的Adapter实例才能获得填充的ArrayList<Model>

一个好的解决方法是在Adapter中使用比尔·皮尤的单例

public class Adapter {
private ArrayList<Model> list;
private Adapter() {}
public static Adapter getInstance() {
return InstInit.INSTANCE;
}
// Don't forget to set the list (or NPE)
// because we can't argue with a Singleton
public void setList(ArrayList<Model> list) {
this.list = list;
}
// You can now get the ArrayList
public ArrayList<Model> getList() {
return list;
}
private static class InstInit {
private static final Adapter INSTANCE = new Adapter();
}
// Some codes removed for brevity
// Overrided RecyclerView.Adapter Methods
.................
}

检索ArrayList假定以下Adapters是单例

AdapterOne a1 = AdapterOne.getInstance();
AdapterTwo a2 = AdapterTwo.getInstance();
ArrayList<Model> a1RetrievedList = a1.getList();
// You don't need to create a new instance
// creating a new instance doesn't make sense
// because you need to repopulate the list
// for the new instance.
ArrayList<Model> a2RetrievedList = a2.getList();
// You can also retrieve from AdapterTwo

最新更新