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

问题描述 投票:1回答:1

实际上,我有一个Recyclerview,其中有一个按钮和(我在其中获取位置[来自RestAPi调用])--- >>当点击按钮时我设置了另一个recylerview ...现在我想要从第一个RecyclerviewAdapter 。我已经尝试过全局变量

这是图像enter image description here

android recycler-adapter
1个回答
0
投票

从我之前的另一个question的答案我认为你需要一个Singleton Pattern而不是一个全局变量

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

一个好的解决方法是在Adapter中使用Bill Pugh的Singleton

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是Singleton,检索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
© www.soinside.com 2019 - 2024. All rights reserved.