问题
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