【问题标题】:How to send data between one adapter to another adapter?如何将一个适配器之间的数据发送到另一个适配器?
【发布时间】:2018-09-06 04:13:49
【问题描述】:

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

这是图片enter image description here

【问题讨论】:

  • 添加一些逻辑代码并简要说明您的问题。
  • 将您的 2 个适配器设置为 1 个适配器 onBindViewHolder()。
  • 请查看我提到的截图。 screenshoot(2) 是第一个适配器,而 screenshoot(3) 是第二个适配器,我想在其中传递我的数据。我尝试了全局验证但它不起作用,数据没有更新。

标签: android android-recyclerview


【解决方案1】:

根据我之前从另一个 question 得到的回答,我认为您需要一个 Singleton Pattern 而不是 全局变量

您只需要一个返回另一个Adapter's ArrayList<SingleItemModel>getter,但您将面临的问题是您需要与Activity 具有相同的Adapter 实例才能获得填充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 假设以下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

【讨论】:

  • 这个答案假设你知道Singleton Pattern
  • 谢谢!!但我已经通过将 id(from restApi) 设置为按钮 id 和 ..get from v.getId(); 解决了它;
猜你喜欢
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2011-12-19
  • 2012-10-30
相关资源
最近更新 更多