簡體   English   中英

如何使用notifyDataSetChanged以最簡單的方式更新recyclerview

[英]How to update recyclerview the simplest way using notifyDataSetChanged

我正在嘗試使用 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 時songAdapter.notifyDataSetChanged(); 數據不會顯示。 我知道我可以通過使用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();

在適配器內部創建一個方法,如

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

在您的類中獲取新值時,使用適配器對象調用該方法

lstSong.updateItems(arrSong);
notifyDataSetChanged();

我不知道您在哪里向RecyclerView.Adapter添加了新項目。 這是添加和設置項目的示例代碼。 更多細節示例 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();
  }

在通知適配器之前,您應該嘗試更新歌曲列表。 例如

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

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

試試這個對我有用。 快樂編碼。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM