Reputation: 1044
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`
}
});
...
Upvotes: 0
Views: 679
Reputation: 5988
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.
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.
You could try moving add("c");
to onPostCreate
or onResume
and you may see similar result as your onClick
.
Upvotes: 1