[英]Why Does RecyclerView Update Without notifyDataSetChanged()?
It is common knowledge to call notifyDataSetChanged()
or notifyItemChanged()
when you mutate an array that is being handled by a RecyclerView adapter in order to update the view and reflect the changes made. 在更改由RecyclerView适配器处理的数组以更新视图并反映所做的更改时,通常会调用
notifyDataSetChanged()
或notifyItemChanged()
。 But I spun up a sample application in which neither are called when I add items to an array immediately after calling .setAdapter()
in the same block, and the view updates! 但是我启动了一个示例应用程序,当我在同一块中调用
.setAdapter()
之后立即向数组中添加项目时,都不调用这两个应用程序,并且视图.setAdapter()
更新! This behavior doesn't happen when I try to add items via a button's onClickListener
or from a background thread (both require notifyDataSetChanged
for the view to update). 当我尝试通过按钮的
onClickListener
或从后台线程添加项目时,都不会发生此行为(均需要notifyDataSetChanged
才能更新视图)。
What's going on here? 这里发生了什么? Shouldn't adding items to the list immediately after calling
.setAdapter()
in the same block require something like notifyDataSetChanged()
? 在同一块中调用
.setAdapter()
之后,是否不应该立即将项目添加到列表中,就需要诸如notifyDataSetChanged()
类的东西?
ie 即
@Override
protected void onCreate(Bundle savedInstanceState) {
...
myList.add("a");
myList.add("b");
recyclerView.setAdapter(adapter);
myList.add("c"); // the recyclerView is updating and shows "c" here! why???
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myList.add("e"); // the recyclerView will NOT update here unless you call `notifyDataSetChanged`
}
});
...
If you're passing an ArrayList
to your Adapter
, and you're adding elements in onCreate
, that would be before the app has drawn your first frame. 如果将
ArrayList
传递给Adapter
,并且要在onCreate
添加元素,那将在应用绘制第一帧之前。
There is a moment where you're able to add elements, because the adapter hasn't laid out the items. 有时您可以添加元素,因为适配器尚未布置项目。
And within your onClick
, that would be after onCreate
has finished, which means the adapter
is already laid out. 在
onClick
,即onCreate
完成之后,这意味着adapter
已经布置好了。
You could try moving add("c");
您可以尝试移动
add("c");
to onPostCreate
or onResume
and you may see similar result as your onClick
. 到
onPostCreate
或onResume
,您可能会看到与onClick
类似的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.