android - 在 recyclerView 中更新项目的最佳方法
问题描述
在我的应用程序中,我使用 RecyclerView 显示提要项目,并在单击该项目时将用户带到另一个显示提要详细信息的活动。
在另一个活动中,用户可以执行一些更改该特定提要的操作。当用户按下返回按钮返回到 RecyclerView 时,项目不会显示更新的数据。
为了解决这个问题,我将 RecyclerView 项目的引用传递给下一个 Activity,并在该引用上调用 update,最终更新 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));
}
推荐阅读
- ios - HTML Drop Down 未在 iPhone 的 IOS 13 中选择选项
- php - 警告:mysqli_stmt_bind_result():绑定变量的数量与准备好的语句中的字段数量不匹配
- javascript - 检测操作系统并重定向到安装的移动应用程序
- flutter - 如何在颤动中将 InputText 转换为 Text Widget
- swift - 来自推送视图控制器的字段为零
- python - why is id([1][::-1]) ==id([1]) returning True while [1][::-1] is [1] returning False?
- swift - 使用 MKMapSnapshotter 创建可点击的地图预览
- pandas - 当列中有重复值时,如何根据索引分配列?
- python - 如何在 selenium python 中抓取突出显示的表数据
- sql - 两列中的 SQL 顺序