public void setAdapter(@Nullable RecyclerView.Adapter adapter) {
this.setLayoutFrozen(false);
//調(diào)用了setAdapterInternal方法
this.setAdapterInternal(adapter, false, true);
this.processDataSetCompletelyChanged(false);
this.requestLayout();
}
private void setAdapterInternal(@Nullable RecyclerView.Adapter adapter, boolean compatibleWithPrevious, boolean removeAndRecycleViews) {
//代碼省略
if (adapter != null) {
//注冊(cè)觀察者
adapter.registerAdapterDataObserver(this.mObserver);
adapter.onAttachedToRecyclerView(this);
}
//代碼省略
}
//這個(gè)觀察者的實(shí)現(xiàn)類(lèi)是RecyclerView的內(nèi)部類(lèi)RecyclerViewDataObserver
private class RecyclerViewDataObserver extends RecyclerView.AdapterDataObserver {
public void onChanged() {
RecyclerView.this.assertNotInLayoutOrScroll((String)null);
RecyclerView.this.mState.mStructureChanged = true;
RecyclerView.this.processDataSetCompletelyChanged(true);
if (!RecyclerView.this.mAdapterHelper.hasPendingUpdates()) {
RecyclerView.this.requestLayout();
}
}
}
在數(shù)據(jù)集發(fā)生變化后調(diào)用了Adapter的notifyDataSetChanged的onChanged函數(shù)后,就會(huì)調(diào)用觀察者的onChanged函數(shù),然后調(diào)用requestLayout方法重新布局。
在方法調(diào)用鏈中,requestLayout()→onLayout()→dispatchLayout()→onLayoutChildren()。
在LinearLayoutManager中,重寫(xiě)了onLayoutChildren(),在onLayoutChildren函數(shù)中會(huì)調(diào)用fill函數(shù),在fill函數(shù)中會(huì)調(diào)用layoutChunk函數(shù)。
//在layoutChunk函數(shù)中獲取了ItemView并且進(jìn)行了布局
void layoutChunk(Recycler recycler, State state, LinearLayoutManager.LayoutState layoutState, LinearLayoutManager.LayoutChunkResult result) {
//在Recycler中獲取Item View
View view = layoutState.next(recycler);
//代碼省略
}
在Recycler中獲取ItemView步驟如下,
1.從mChangedScrap中獲取ViewHolder緩存,
2.從mAttachedScrap中獲取ViewHolder緩存
3.沒(méi)有ViewHolder函數(shù),會(huì)調(diào)用onCreateViewHolder函數(shù),
4.綁定數(shù)據(jù),則調(diào)用Adapter的onBindViewHolder
總結(jié): Recyclew通過(guò)適配器模式和觀察者模式,進(jìn)行數(shù)據(jù)綁定,
Adapter封裝了ViewHolder的創(chuàng)建和綁定,而將布局工作交給了LayoutManager,在LayoutManager中進(jìn)行ItemView的布局。