notifyDataSetChanged vs setAdapter

后端 未结 2 851
暗喜
暗喜 2020-12-31 10:55

I know that it is more efficient to use notifyDataSetChanged, when I want adapter to show updated data. However, due to my design I am thinkig about resetting adapter each t

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 10:59

    A bit late, but I didn't like Ragnar's response, because it doesn't explain everything.

    Basically,

    myListAdapter.notifyDataSetChanged() 
    

    vs

    setListAdapter(new ArrayAdapter(myList));
    

    will be pretty much similar in performance (notifyDataSetChanged is not all that innocent: debug step-by-step to see that it triggers all change observers - each element of the underlying list - to inform them about changes).

    Performance is not what you are after in this case. Depending on the overall structure of the project, both can be more or less readable/maintainable. Main difference though, is the fact that by recreating an adapter you lose the state of the existing one. State undermines the product of user interaction with the list - scroll position, row selection, changes that may be have been introduced during interaction.

    To conclude, if your design suggests that you should recreate and reassign the Adapter, you can just keep that implementation. More reliable and user friendly is to invoke notifyDataSetChange though.

    Suggestions of kind

    You should think about a change of design.

    are nice to say but not always applicable (e.g. one may be working in a team or maintaining an application where he's got no control/resources to reimplement everything).

提交回复
热议问题