RecyclerView适配器notifyDataSetChanged无法正常工作

问题描述 投票:26回答:7

我延长了

RecyclerView.Adapter<RecyclerView.ViewHolder>

当我打电话的时候:

mRecyclerView.getAdapter().notifyDataSetChanged();

没啥事儿。

刷新视图的唯一方法是再次设置适配器(see this answer):

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

这个解决方案有两个问题:

  1. 当我再次设置适配器时,我可以看到屏幕上闪烁
  2. 列表视图返回第一个位置。

有任何想法吗?

android android-adapter android-recyclerview notifydatasetchanged
7个回答
26
投票

如果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)之前;


24
投票

如果你的getItemCount()返回0,那么notifyDataSetChanged()将不会做任何事情。确保在初始化适配器时传递有效数据集。


4
投票

根据javadocs:如果你正在编写适配器,如果可以的话,使用更具体的更改事件总是更有效。依靠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);

2
投票

要更新recyclerview,我们可以执行以下操作:

  1. 再次创建和设置适配器: adapter=new MyAdapter(...); mRecyclerView.setAdapter(adapter);
  2. 清除模型列表数据然后通知: List<YourModel> tempModel=new ArrayList<>(modelList); modelList.clear(); modelList.addAll(tempModel); adapter.notifyDataSetChanged();

0
投票

想要分享一些东西,我遇到了同样的问题。但我做错了是。我每次都在创建适配器实例,而不是对新实例执行notifysetDatachange()而不是旧实例。

因此,请确保您notifysetDatachange()的适配器应该更旧。希望下面的例子帮助..

     MyAdapter mAdapter = new MyAdapter(...)

    mRecyclerView.setAdapter(mAdapter );

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


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

    }

    }

0
投票

所以我修复了我的问题:orderList是我传递给recyclerview的List。我们可以在列表中的位置添加项目,这里0是列表中的第0个位置。然后调用adapter.notifyDataSetChanged()。奇迹般有效

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


-2
投票

应该在主线程中调用notifyDataSetChanged()。

© www.soinside.com 2019 - 2024. All rights reserved.