实际上,我有一个Recyclerview,其中有一个按钮和(我在其中获取位置[来自RestAPi调用])--- >>当点击按钮时我设置了另一个recylerview ...现在我想要从第一个RecyclerviewAdapter 。我已经尝试过全局变量
从我之前的另一个question的答案我认为你需要一个
Singleton Pattern
而不是一个全局变量
你只需要一个返回另一个getter
Adapter's
的ArrayList<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