適配器模式—在RecyclerView源碼的應(yīng)用

   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) {
            //注冊觀察者
            adapter.registerAdapterDataObserver(this.mObserver);
            adapter.onAttachedToRecyclerView(this);
        }
       //代碼省略
    }
   
//這個觀察者的實現(xiàn)類是RecyclerView的內(nè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ù)后,就會調(diào)用觀察者的onChanged函數(shù),然后調(diào)用requestLayout方法重新布局。

在方法調(diào)用鏈中,requestLayout()→onLayout()→dispatchLayout()→onLayoutChildren()。
在LinearLayoutManager中,重寫了onLayoutChildren(),在onLayoutChildren函數(shù)中會調(diào)用fill函數(shù),在fill函數(shù)中會調(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.沒有ViewHolder函數(shù),會調(diào)用onCreateViewHolder函數(shù),
4.綁定數(shù)據(jù),則調(diào)用Adapter的onBindViewHolder

總結(jié): Recyclew通過適配器模式和觀察者模式,進(jìn)行數(shù)據(jù)綁定,
Adapter封裝了ViewHolder的創(chuàng)建和綁定,而將布局工作交給了LayoutManager,在LayoutManager中進(jìn)行ItemView的布局。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容