BaseAdapter.notifyDataSetChanged()的实现涉及到设计模式-观察者模式,详情请参考我之前的博文设计模式之观察者模式
Ok,回到notifyDataSetChanged进行源码分析,
Adapter本身不是被观察者Observable,而是adapter里面有一个被观察者DataSetObservable mDataSetObservable
public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); }
notifyChanged源码分析,notifyChanged实际上是去调用了观察者Observer的onChanged方法.
1 public void notifyChanged() { 2 synchronized(mObservers) { 3 // since onChanged() is implemented by the app, it could do anything, including 4 // removing itself from {@link mObservers} - and that could cause problems if 5 // an iterator is used on the ArrayList {@link mObservers}. 6 // to avoid such problems, just march thru the list in the reverse order. 7 for (int i = mObservers.size() - 1; i >= 0; i--) { 8 mObservers.get(i).onChanged(); 9 } 10 } 11 }
被观察者subject ListAdapter添加注册观察者Observer AdapterDataSetObserver
1 //ListView.java - setAdapter()
2 //被观察者subject ListAdapter添加注册观察者Observer AdapterDataSetObserver
3 mDataSetObserver = new AdapterDataSetObserver();
4 mAdapter.registerDataSetObserver(mDataSetObserver);
AdapterDataSetObserver的onChanged方法里最后调用了requestLayout去更新ListView
1 //AdapterView.java 2 class AdapterDataSetObserver extends DataSetObserver { 3 4 private Parcelable mInstanceState = null; 5 6 @Override 7 public void onChanged() { 8 mDataChanged = true; 9 mOldItemCount = mItemCount; 10 mItemCount = getAdapter().getCount(); 11 12 // Detect the case where a cursor that was previously invalidated has 13 // been repopulated with new data. 14 if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null 15 && mOldItemCount == 0 && mItemCount > 0) { 16 AdapterView.this.onRestoreInstanceState(mInstanceState); 17 mInstanceState = null; 18 } else { 19 rememberSyncState(); 20 } 21 checkFocus(); 22 requestLayout(); 23 } 24 25 @Override 26 public void onInvalidated() { 27 mDataChanged = true; 28 29 if (AdapterView.this.getAdapter().hasStableIds()) { 30 // Remember the current state for the case where our hosting activity is being 31 // stopped and later restarted 32 mInstanceState = AdapterView.this.onSaveInstanceState(); 33 } 34 35 // Data is invalid so we should reset our state 36 mOldItemCount = mItemCount; 37 mItemCount = 0; 38 mSelectedPosition = INVALID_POSITION; 39 mSelectedRowId = INVALID_ROW_ID; 40 mNextSelectedPosition = INVALID_POSITION; 41 mNextSelectedRowId = INVALID_ROW_ID; 42 mNeedSync = false; 43 44 checkFocus(); 45 requestLayout(); 46 } 47 48 public void clearSavedState() { 49 mInstanceState = null; 50 } 51 }