一.BaseAdapter內部設有觀察者機制java
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter { private final DataSetObservable mDataSetObservable = new DataSetObservable(); public void registerDataSetObserver(DataSetObserver observer) { mDataSetObservable.registerObserver(observer); } public void unregisterDataSetObserver(DataSetObserver observer) { mDataSetObservable.unregisterObserver(observer); //刷新界面和數據 } public void notifyDataSetChanged() { mDataSetObservable.notifyChanged(); //刷新界面 } public void notifyDataSetInvalidated() { mDataSetObservable.notifyInvalidated(); } /** *一下省略到一大片成員變量 *方法數(何止一二個) *變量(反正已知的很少) */ }
其中咱們看到了android
--觀察者集合容器網絡
DataSetObservable
--觀察者ide
public abstract class DataSetObserver { public void onChanged() { // Do nothing } public void onInvalidated() { // Do nothing } }
二,應用動畫
首先:這些觀察者廣泛存在於BaseAdapter,FragmentPagerAdapter,PagerAdapter,RecyclerView.Adapter中,主要是爲了配合適配器更新數據this
應用一.RecylerView中的EmptyViewcode
public class RecyclerViewEmptySupport extends RecyclerView { private View emptyView; private AdapterDataObserver emptyObserver = new AdapterDataObserver() { @Override public void onChanged() { Adapter<?> adapter = getAdapter(); if(adapter != null && emptyView != null) { if(adapter.getItemCount() == 0) { emptyView.setVisibility(View.VISIBLE); RecyclerViewEmptySupport.this.setVisibility(View.GONE); } else { emptyView.setVisibility(View.GONE); RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE); } } } }; public RecyclerViewEmptySupport(Context context) { super(context); } public RecyclerViewEmptySupport(Context context, AttributeSet attrs) { super(context, attrs); } public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setAdapter(Adapter adapter) { super.setAdapter(adapter); if(adapter != null) { adapter.registerAdapterDataObserver(emptyObserver); } emptyObserver.onChanged(); } public void setEmptyView(View emptyView) { this.emptyView = emptyView; }}
xmlserver
<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1" android:layout_height="match_parent" android:layout_width="match_parent" /><TextView android:id="@+id/list_empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Empty" />
Activityxml
RecyclerViewEmptySupport list = (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1); list.setLayoutManager(new LinearLayoutManager(context)); list.setEmptyView(rootView.findViewById(R.id.list_empty));
應用二,咱們能夠經過註冊觀察者,判斷數據變化咱們能夠減小判斷,特別在加載網絡數據的時候get
應用三,咱們能夠在數據變化時開始某一類動畫