标签:
ListView要想显示数据,需要用到数据适配器即Adapter。而当我们删除ListView的某个条目时,数据适配器中的数据源必然发生改变,这时候我们通过调用适配器类提供的notifyDataSetChanged方法通知listview数据发生改变,请求重新绘制。public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); }这个mDataSetObservable即被观察的对象,它是一个DataSetObservable类型。我们来看下其实现:
package android.database; public class DataSetObservable extends Observable<DataSetObserver> { public void notifyChanged() { synchronized(mObservers) { for (int i = mObservers.size() - 1; i >= 0; i--) { mObservers.get(i).onChanged(); } } } }
package android.database; import java.util.ArrayList; public abstract class Observable<T> { protected final ArrayList<T> mObservers = new ArrayList<T>(); public void registerObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { if (mObservers.contains(observer)) { throw new IllegalStateException("Observer " + observer + " is already registered."); } mObservers.add(observer); } } public void unregisterObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { int index = mObservers.indexOf(observer); if (index == -1) { throw new IllegalStateException("Observer " + observer + " was not registered."); } mObservers.remove(index); } } ... }
public void setAdapter(ListAdapter adapter) { ... ... super.setAdapter(adapter); if (mAdapter != null) { ... ... mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); ... ... } else { ... ... } requestLayout(); }果然,在这个方法中我们找到了注册观察者的代码,但是这里的观察者是AdapterDataSetObserver类型的,而Adapter要求的是DataSetObserver类型的,那么很显然,AdapterDataSetObserver是DataSetObserver的子类。该类的定义在ListView的父类AbsListView中:
class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver { @Override public void onChanged() { super.onChanged(); if (mFastScroller != null) { mFastScroller.onSectionsChanged(); } } ... ... }而AbsListView中的AdapterDataSetObserver又继承了AdapterView类中的AdapterDataSetObserver。最终,我们再AdapterView中找到AdapterDataSetObserver:
class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0) { AdapterView.this.onRestoreInstanceState(mInstanceState); mInstanceState = null; } else { rememberSyncState(); } checkFocus(); requestLayout(); } ... ... }
标签:
原文地址:http://blog.csdn.net/chdjj/article/details/42293681