首页 > 解决方案 > 在 recyclerView 中更新项目的最佳方法

问题描述

在我的应用程序中,我使用 RecyclerView 显示提要项目,并在单击该项目时将用户带到另一个显示提要详细信息的活动。

在另一个活动中,用户可以执行一些更改该特定提要的操作。当用户按下返回按钮返回到 RecyclerView 时,项目不会显示更新的数据。

为了解决这个问题,我将 RecyclerView 项目的引用传递给下一个 Activity,并在该引用上调用 update,最终更新 RecyclerView 项目中的提要。

这是正确的方法还是有更好的方法?

标签: androidandroid-recyclerview

解决方案


您可以向您的 recylerview 适配器发送消息。只需检查此库;事件总线

创建用于数据传输的模型

public class YourModel {

int id;
String updateValue;


public YourModel(int id, String value) {
    this.id = id;
    this.updateValue = value;
}

public int getId() {
    return id;
}

public void setId(int id) {
     this.id = id;
}

 public String getValue() {
    return updateValue;
}

public void setValue(String value) {
     this.updateValue = value;
}

}

主要活动;

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(YourModel model) {
    int updateIndex = model.getId();
    String newValue = model.getValue();
    arraylist.set(updateIndex, newValue);
    adapter.notifyItemChanged(updateIndex);
}

并为您的详细活动

@Override
public void onBackPressed() {
    super.onBackPressed();
    EventBus.getDefault().postSticky(new YourModel(yourItemPosition, yourNewUpdates));
}

推荐阅读