2017-10-12 83 views
-4

我想使用notifyDataSetChanged()更新我的recyclerview,但它不起作用。我正在將適配器設置爲recyclerview,如下所示:如何使用notifyDataSetChanged更新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();的回收站時,數據不會顯示出來。我知道我可以通過使用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(); 
+0

可以分享您的代碼,您在回收站中添加新物品 –

+0

我可以看到您的SongAdapter代碼檢查如何添加新項目嗎? – kimkevin

+0

而不是arrSong = kFunc.getAllSong();這個使用arrSong.addAll(kFunc.getAllSong()); –

回答

0

創建內部適配器的方法類似

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

雖然在你的班上獲得新的價值使用adapdter對象

lstSong.updateItems(arrSong); 
notifyDataSetChanged(); 
+0

我做了類似於我的適配器的構造函數 –

+0

是的構造函數是隻有第一次。當數據更改您必須通過該方法再次更新引用。添加此方法裏面你的adatper並從課堂上調用它。 – Anonymous

0

我不調用該方法知道您將新項目添加到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(); 
    } 
0

你應該通過更新歌曲的列表,則通知適配器之前嘗試。 例如

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

,如果你在ListView控件,你不但是隻有你的信息。
adapter.lstSong =<updated songs List>; adapter.notifyDataStteChanged();

試試這個工作適合我。 快樂編碼。 :)

+0

這就是即時通訊使用。看看我的更新 –

+0

@RickyManalo你應該嘗試更新適配器內部的列表。 –

+0

就像在更新列表的適配器內創建一個方法。然後嘗試通知適配器 –