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. 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! 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).
What's going on here? Shouldn't adding items to the list immediately after calling .setAdapter()
in the same block require something like notifyDataSetChanged()
?
i.e.
@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`
}
});
...