【问题标题】:Recycler view adapter not reflecting changes回收站视图适配器不反映更改
【发布时间】:2014-12-24 20:13:06
【问题描述】:

所以我在我的 MainActivity 中设置了一个回收器视图适配器。该适配器已连接到我创建的名为 group 的自定义对象的数组列表。

public static RecyclerView.Adapter groupsListAdapter;
public ArrayList<Group> myGroups;

//在主Activity的onCreate里面

groupsListAdapter = new MyAdapter(myGroups);

在另一个活动中,我正在更新这个数组列表的内容,首先是通过意图传递它。

Intent groupCreationIntent = new Intent(MainActivity.this, NewGroupActivity.class);
        groupCreationIntent.putExtra("groupsList",myGroups);
        startActivity(groupCreationIntent);

然后在其他活动中更新它。

private ArrayList<Group> groups;

//在其他activity的oncreate方法中

groups = (ArrayList<Group>) getIntent().getSerializableExtra("groupsList");

当返回上一个活动时(第二个活动用于输入一些信息并将其与我的数据库同步),我运行此代码。

groups.add(myGroup);
MainActivity.groupsListAdapter.notifyDataSetChanged();
finish();

问题是列表适配器没有反映更改,一旦我返回主要活动,我的列表中就没有出现任何内容。我做错了什么?

【问题讨论】:

  • 如果一个数组列表正在被填充,那么最好在得到结果后对主要活动进行 notifydataset 更改的最后一部分。
  • 您是否查看过其他关于 notifydatasetchange() 未反映更改的帖子?

标签: android android-recyclerview


【解决方案1】:
class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  private List<Group> items;

  public MyAdapter(List<Group> items) {
    this.items = items;
  }

  // .. your implementation

  // add and call this
  public void add(Group item) {
    this.items.add(item);
    notifyItemInserted(items.size() - 1);
  }
}

这与您的问题无关,您不应使用静态字段进行活动到活动的通信。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多