android ArrayAdapter.setNotifyOnChange(false) does not prevent listView from refreshing

爷,独闯天下 提交于 2019-12-24 10:15:23

问题


I have a listview with an arrayadapter. I want to refresh the adapter when I entirely fill in my array of items and only at this time. I know that notifyDataSetChanged() will be automatically called after methods such as add, addAll, remove, insert or clear but I think there might be a bug in my case. Here is a simple snippet of code that should work. I mean in this case the adapter should not notify its ListView and content sould not be displayed (but content is displayed on my device).

ArrayList<MenuFragmentItem> menu = buildMenu();
MenuAdapter mAdapter = new MenuAdapter(getActivity().getApplicationContext(), 0, MenuFragment.this);
mListView.setAdapter(mAdapter);
mAdapter.setNotifyOnChange(false);
mAdapter.clear();
mAdapter.addAll(menu);
//      mAdapter.notifyDataSetChanged(); SAME RESULT IF I REMOVE THIS LINE, CONTENT IS DISPLAYED

Any idea on this issue?


回答1:


If you look at the ListView source code, you'll see that setAdapter sets mDataChanged and calls requestLayout, which will schedule a layout. Your adapter won't be read back until that layout occurs, which will be after your clear and addAll code executes.

http://gitorious.org/android-eeepc/base/blobs/3661101005c6527dfd384d0c88c4a3b68ee208af/core/java/android/widget/ListView.java

There are also several other ways to cause mDataChanged to be set to true and a new requestLayout call, such as checking, focusing, or selecting an item. Calling notifyDataSetChanged just makes that happen immediately:

http://gitorious.org/android-eeepc/base/blobs/3661101005c6527dfd384d0c88c4a3b68ee208af/core/java/android/widget/AdapterView.java#line772

    public void onChanged() {
        mDataChanged = true;
        ...
        requestLayout();
    }


来源:https://stackoverflow.com/questions/10881093/android-arrayadapter-setnotifyonchangefalse-does-not-prevent-listview-from-ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!