RecyclerView Adapter notifyDataSetChanged 不起作用 [英] RecyclerView Adapter notifyDataSetChanged not working
问题描述
我延长了
RecyclerView.Adapter<RecyclerView.ViewHolder>
当我打电话时:
mRecyclerView.getAdapter().notifyDataSetChanged();
什么都没发生.
刷新视图的唯一方法是再次设置适配器(看到这个答案):
The only way to refresh the view is to set again the adapter (see this answer):
mRecyclerView.setAdapter(new MyAdapter(...));
我对这个解决方案有两个问题:
I have two issues with this solution:
- 当我重新设置适配器时,我可以看到屏幕上闪烁
- 列表视图返回到第一个位置.
有什么想法吗?
推荐答案
如果 notifyDataSetChanged()
没有触发视图更新,那么您可能忘记调用 SetLayoutManager()
在你的 RecyclerView 上(就像我做的!).只是不要忘记这样做:Java 代码:
If notifyDataSetChanged()
does not trigger view updates than there is a chance that you have forgotten to call SetLayoutManager()
on your RecyclerView (like I did!).
Just don't forget to do this:
Java code:
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)
;
如果你更喜欢在 xml 中声明它,所以你不能在代码中忘记它,你也可以将这些行添加到你的 recyclerView 的 xml 中:
If you prefer declaring it in xml, so you cannot forget it in the code you can also add these lines to the xml of your recyclerView:
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="vertical"
这篇关于RecyclerView Adapter notifyDataSetChanged 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!