0

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`
            }
        });

        ...
Grant Park
  • 1,004
  • 1
  • 9
  • 29

1 Answers1

1

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.

advice
  • 5,778
  • 10
  • 33
  • 60
  • do you happen to have a source or reference for when you mentioned "because the adapter hasn't laid out the items"? – Grant Park Feb 23 '19 at 03:35
  • @GrantPark No, I do not. It's just the Android lifecycle, and `onCreate` is before the actual layout is laid out. For example, if you tried to get your height/width of your `RecyclerView` in `onCreate`, it'd return 0. You can check out something like this, https://stackoverflow.com/a/7735122/3106174, which shows you can get a callback to when it's actually laid out. – advice Feb 25 '19 at 18:13