簡體   English   中英

RecyclerView適配器notifyDataSetChanged不起作用

[英]RecyclerView Adapter notifyDataSetChanged not working

我延長了

RecyclerView.Adapter<RecyclerView.ViewHolder>

當我打電話時:

mRecyclerView.getAdapter().notifyDataSetChanged();

沒啥事兒。

刷新視圖的唯一方法是再次設置適配器( 請參見此答案 ):

mRecyclerView.setAdapter(new MyAdapter(...));

這個解決方案有兩個問題:

  1. 再次設置適配器時,我可以在屏幕上看到閃爍的光
  2. 列表視圖返回到第一個位置。

有任何想法嗎?

如果notifyDataSetChanged()沒有觸發視圖更新,則有可能您忘記了在RecyclerView上調用SetLayoutManager() (就像我一樣!)。 只是不要忘記這樣做: Java代碼:

LinearLayoutManager layoutManager = new LinearLayoutManager(context ,LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager)

C#代碼,我正在使用Xamarin。

var layoutManager = new LinearLayoutManager(Context, LinearLayoutManager.Vertical, false);
recyclerView.SetLayoutManager(layoutManager);

在調用recyclerView.SetAdapter(adapter)

如果您的getItemCount()返回0,則notifyDataSetChanged()將不執行任何操作。 確保在初始化適配器時傳遞有效的數據集。

根據javadocs:如果您正在編寫適配器,那么如果可以的話,使用更具體的更改事件將總是更加高效。 notifyDataSetChanged()不得已時,請依賴notifyDataSetChanged()

public class NewsAdapter extends RecyclerView.Adapter<...> {    

private static List mFeedsList;
...

    public void swap(List list){
    if (mFeedsList != null) {
        mFeedsList.clear();
        mFeedsList.addAll(list);
    }
    else {
        mFeedsList = list;
    }
    notifyDataSetChanged();
}

我正在使用Retrofit來獲取列表,在Retrofit的onResponse()使用中,

adapter.swap(feedList);

要更新recyclerview,我們可以執行以下操作:

  1. 再次創建並設置適配器:

     adapter=new MyAdapter(...); mRecyclerView.setAdapter(adapter); 
  2. 清除模型列表數據,然后通知:

     List<YourModel> tempModel=new ArrayList<>(modelList); modelList.clear(); modelList.addAll(tempModel); adapter.notifyDataSetChanged(); 

想分享一些東西,我面臨着同樣的問題。 但是我做錯了。 我每次都創建Adapter實例,而不是對那個新實例而不是較舊的實例做notifysetDatachange()。

因此,請確保您要通知誰的AdaptersetDataData()應該較舊。 希望下面的例子有幫助。

     MyAdapter mAdapter = new MyAdapter(...)

    mRecyclerView.setAdapter(mAdapter );

// TODO 
mAdapter.modifyData(....);
mAdapter.notifySetDataChange();


    MyAdapter extends baseAdapter {
     MyAdapter () {
    }
    modifyData(String[] listData) {

    }

    }

所以我解決了這樣的問題:orderList是我傳遞給recyclerview的列表。 我們可以將項目添加到列表中的位置,這里0是列表中的第0個位置。 然后調用adapter.notifyDataSetChanged()。 奇跡般有效

1)orderList.add(0,String); 2)orderAdapter.notifyDataSetChanged();

就我而言,這沒有任何作用。 當需要刷新RecyclerView ,我做了:

array = getNewItems();                    // populates the list with new items
((MyAdapter) mAdapter).setValues(array);  // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();          // tell the adapter a data set has changed

MyAdapter ,我將setter放入了數據中:

public void setValues(List<Item> items){
    this.items = items;
}

而已!

[ 請注意 ,在沒有為適配器設置新值的情況下notifyDataSetChanged無效。

應該在主線程中調用notifyDataSetChanged()。

暫無
暫無

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

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