我延长了
RecyclerView.Adapter<RecyclerView.ViewHolder>
当我打电话的时候:
mRecyclerView.getAdapter().notifyDataSetChanged();
没啥事儿。
刷新视图的唯一方法是再次设置适配器(see this answer):
mRecyclerView.setAdapter(new MyAdapter(...));
这个解决方案有两个问题:
有任何想法吗?
如果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()
作为最后的手段。
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,我们可以执行以下操作:
adapter=new MyAdapter(...);
mRecyclerView.setAdapter(adapter);
List<YourModel> tempModel=new ArrayList<>(modelList);
modelList.clear();
modelList.addAll(tempModel);
adapter.notifyDataSetChanged();
想要分享一些东西,我遇到了同样的问题。但我做错了是。我每次都在创建适配器实例,而不是对新实例执行notifysetDatachange()而不是旧实例。
因此,请确保您notifysetDatachange()的适配器应该更旧。希望下面的例子帮助..
MyAdapter mAdapter = new MyAdapter(...)
mRecyclerView.setAdapter(mAdapter );
// TODO
mAdapter.modifyData(....);
mAdapter.notifySetDataChange();
MyAdapter extends baseAdapter {
MyAdapter () {
}
modifyData(String[] listData) {
}
}
所以我修复了我的问题:orderList是我传递给recyclerview的List。我们可以在列表中的位置添加项目,这里0是列表中的第0个位置。然后调用adapter.notifyDataSetChanged()。奇迹般有效
1)orderList.add(0,String); 2)orderAdapter.notifyDataSetChanged();
应该在主线程中调用notifyDataSetChanged()。