【问题标题】:How to update recyclerview the simplest way using notifyDataSetChanged如何使用 notifyDataSetChanged 以最简单的方式更新 recyclerview
【发布时间】:2017-10-12 08:43:51
【问题描述】:

我正在尝试使用 notifyDataSetChanged() 更新我的 recyclerview,但它不起作用。我将适配器设置为 recyclerview,如下所示:

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false);
lstSong.setLayoutManager(mLayoutManager);
lstSong.setItemAnimator(new DefaultItemAnimator());
lstSong.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(0), true));

arrSong = new ArrayList<Song>();
arrSong = kFunc.getAllSong();
songAdapter = new SongAdapter(ctx, arrSong);
lstSong.setAdapter(songAdapter);

这行代码显示数据。但是当我添加一个新数据并使用songAdapter.notifyDataSetChanged(); 刷新recyclerview 时,数据不会显示。我知道我可以使用setAdapter() 来显示它,但我想正确地做到这一点。

我在刷新之前添加数据。这是代码:

kFunc = new Function(ctx);
Song song = new Song();
song.setTitle(title);
song.setArtist(artist);
song.setYear_released(yearReleased);
song.setAlbum(album);
song.setGenre(genre);
song.setDuration(duration);
song.setCode(code);
song.setLyrics(lyrics);

kFunc.addSong(song);
dialog.dismiss();

arrSong = kFunc.getAllSong();
songAdapter.notifyDataSetChanged();

【问题讨论】:

  • 可以分享你在recyclerview中添加新项目的代码
  • 我可以看看你的 SongAdapter 代码来检查如何添加新项目吗?
  • 而不是 arrSong = kFunc.getAllSong();这个使用 arrSong.addAll(kFunc.getAllSong());
  • 哇,@JRamesh 成功了。这是我第一次使用该代码。在我记得我刚刚使用 notifyDataSetChanged() 之前

标签: android android-recyclerview


【解决方案1】:

在适配器内部创建一个方法

public updateItems(ArrayList<Song> songs){
    arrSong=songs;
}

在你的类中获取新值时,使用adapdter对象调用方法

lstSong.updateItems(arrSong);
notifyDataSetChanged();

【讨论】:

  • 我正在做与适配器构造函数中类似的事情
  • 是的,构造函数只是第一次。当数据更改时,您必须通过该方法再次更新引用。将此方法添加到您的adatper中并从类中调用它。
【解决方案2】:

我不知道你在哪里向RecyclerView.Adapter 添加了新项目。这是添加和设置项目的示例代码。更多详情Sample RecyclerViewAdapter

  @Override
  public void addItem(M item) {
    items.add(item);
    notifyItemInserted(items.size() - 1);
  }

  @Override
  public void addItem(int position, M item) {
    items.add(position, item);
    notifyItemInserted(position);
  }

  @Override
  public void addAllItems(List<M> items) {
    this.items.addAll(items);
    notifyDataSetChanged();
  }

  @Override
  public void setItems(List<M> items) {
    this.items = items;
    notifyDataSetChanged();
  }

【讨论】:

    【解决方案3】:

    您应该在通知适配器之前尝试更新歌曲列表。 例如

    arraySongs = <retrive updated data of the song>; adapter.notifyDataStateChanged()

    如果您在 ListView 中,但您不是,仅供参考。
    adapter.lstSong =<updated songs List>; adapter.notifyDataStteChanged();

    试试这个对我有用。 快乐编码。 :)

    【讨论】:

    • @RickyManalo 您应该尝试更新适配器内部的列表。
    • 就像在适配器内部创建一个更新列表的方法。然后尝试通知适配器
    • 为什么我需要创建一个更新列表的方法?适配器不应该只显示数据吗
    • 也许该列表是私有的,因此您无法在类(适配器)之外访问该列表,但您也可以通过简单的adapter.lstSongs = &lt;updated song List&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2016-11-17
    相关资源
    最近更新 更多