简体   繁体   中英

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. 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() ?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM