RecyclerView定制:通用ItemDecoration及全展開RecyclerView的實現

Android L面世之后,Google就推薦在開發項目中使用RecyclerView來取代ListView,因為RecyclerView的靈活性跟性能都要比ListView更強,但是,帶來的問題也不少,比如:列表分割線都要開發者自己控制,再者,RecyclerView的測量與布局的邏輯都委托給了自己LayoutManager來處理,如果需要對RecyclerView進行改造,相應的也要對其LayoutManager進行定制。本文主要就以以下場景給出RecyclerView使用參考:

RecyclerView的幾種常用場景

  • 如何實現帶分割線的列表式RecyclerView
  • 如何實現帶分割線網格式RecyclerView
  • 如何實現全展開的列表式RecyclerView(比如:嵌套到ScrollView中使用)
  • 如何實現全展開的網格式RecyclerView(比如:嵌套到ScrollView中使用)

先看一下實現樣式,為了方便控制,邊界的均不設置分割線,方便定制,如果需要可以采用Padding或者Margin來實現。Github連接 RecyclerItemDecoration

網格式列表樣式
全展開的網格式列表

全展開的線性列表

不同場景RecyclerView實現

默認的縱向列表式RecyclerView

首先看一下最簡單的縱向線性RecyclerView,一般用以下代碼:

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(linearLayoutManager);

以上就是最簡單的線性RecyclerView的實現,但默認不帶分割線,如果想要使用比如20dp的黑色作為分割線,就需要自己定制,Google為RecyclerView提供了ItemDecoration,它的作用就是為Item添加一些附屬信息,比如:分割線,浮層等。

帶分割線的列表式RecyclerView--LinearItemDecoration

RecyclerView提供了addItemDecoration接口與ItemDecoration類用來定制分割線樣式,那么,在RecyclerView源碼中,是怎么用使用ItemDecoration的呢。與普通View的繪制流程一致,RecyclerView也要經過measure->layout->draw,并且在measure、layout之后,就應該按照ItemDecoration的限制,為RecyclerView的分割線挪出空間。RecyclerView的measure跟Layout其實都是委托給自己的LayoutManager的,在LinearLayoutManager測量或者布局時都會直接或者間接調用RecyclerView的measureChildWithMargins函數,而measureChildWithMargins函數會進一步找到addItemDecoration添加的ItemDecoration,通過其getItemOffsets函數獲取所需空間信息,源碼如下:

  public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
      final LayoutParams lp = (LayoutParams) child.getLayoutParams();

      final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
      widthUsed += insets.left + insets.right;
      heightUsed += insets.top + insets.bottom;

      final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
              getPaddingLeft() + getPaddingRight() +
                      lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
              canScrollHorizontally());
      final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
              getPaddingTop() + getPaddingBottom() +
                      lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
              canScrollVertically());
      if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
          child.measure(widthSpec, heightSpec);
      }
  }

可見measureChildWithMargins會首先通過getItemDecorInsetsForChild計算出每個child的ItemDecoration所限制的邊界信息,之后將邊界所需的空間作為已用空間為child構造MeasureSpec,最后用MeasureSpec對child進行尺寸測量:child.measure(widthSpec, heightSpec);來看一下getItemDecorInsetsForChild函數:

Rect getItemDecorInsetsForChild(View child) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (!lp.mInsetsDirty) {
        return lp.mDecorInsets;
    }

    final Rect insets = lp.mDecorInsets;
    insets.set(0, 0, 0, 0);
    final int decorCount = mItemDecorations.size();
    for (int i = 0; i < decorCount; i++) {
        mTempRect.set(0, 0, 0, 0);
        <!--通過這里知道,需要繪制的空間位置-->
        mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
        insets.left += mTempRect.left;
        insets.top += mTempRect.top;
        insets.right += mTempRect.right;
        insets.bottom += mTempRect.bottom;
    }
    lp.mInsetsDirty = false;
    return insets;
}

一般而言,不會同時設置多類ItemDecoration,太麻煩,對于普通的線性布局列表,其實就簡單設定一個自定義ItemDecoration即可,其中outRect參數主要是控制每個Item上下左右的分割線所占據的寬度跟高度,這個尺寸跟繪制的時候的尺寸應該對應(如果需要繪制的話),看一下LinearItemDecoration的getItemOffsets實現:

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == VERTICAL_LIST) {
    
    <!--垂直方向 ,最后一個不設置padding-->
        if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount()1) {
            outRect.set(0, 0, 0, mSpanSpace);
        } else {
            outRect.set(0, 0, 0, 0);
        }
    } else {
     <!--水平方向 ,最后一個不設置padding-->
        if (parent.getChildAdapterPosition(view) < parent.getAdapter().getItemCount()1) {
            outRect.set(0, 0, mSpanSpace, 0);
        } else {
            outRect.set(0, 0, 0, 0);
        }
    }
}   

measure跟layout之后,再來看一下RecyclerView的onDraw函數, RecyclerView在onDraw函數中會調用ItemDecoration的onDraw,繪制分割線或者其他輔助信息,ItemDecoration 支持上下左右四個方向定制占位分割線等信息,具體要繪制的樣式跟位置都完全由開發者確定,所以自由度非常大,其實如果不是太特殊的需求的話,onDraw函數完全可以不做任何處理,僅僅用背景色就可以達到簡單的分割線的目的,當然,如果想要定制一些特殊的圖案之類的需話,就需要自己繪制,來看一下LinearItemDecoration的onDraw(只看Vertical的)

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == VERTICAL_LIST) {
        drawVertical(c, parent);
    } else {
       ...
    }
}

其實,如果不是特殊的繪制需求,比如顯示七彩的,或者圖片,完全不需要任何繪制,如果一定要繪制,注意繪制的尺寸區域跟原來getItemOffsets所限制的區域一致,繪制的區域過大不僅不會顯示出來,還會引起過度繪制的問題:

public void drawVertical(Canvas c, RecyclerView parent) {                              int totalCount = parent.getAdapter().getItemCount();            final int childCount = parent.getChildCount();              for (int i = 0; i < childCount; i++) {                  final View child = parent.getChildAt(i);                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child                          .getLayoutParams();                 final int top = child.getBottom() + params.bottomMargin +                           Math.round(ViewCompat.getTranslationY(child));                  final int bottom = top + mVerticalSpan;                         final int left = child.getLeft() + params.leftMargin;                   final int right = child.getRight() + params.rightMargin;                        if (!isLastRaw(parent, i, mSpanCount, totalCount))                      if (childCounti > mSpanCount) {                         drawable.setBounds(left, top, right, bottom);                           drawable.draw(c);            }       
    }       
}

帶分割線的網格式RecyclerView--GridLayoutItemDecoration

網格式RecyclerView的處理流程跟上面的線性列表類似,不過網格式的需要根據每個Item的位置為其設置好邊距,比如最左面的不需要左邊占位,最右面的不需要右面的占位,最后一行不需要底部的占位,如下圖所示

網格式ItemDocration的限制

RecyclerView的每個childView都會通過getItemOffsets來設置自己ItemDecoration,對于網格式的RecyclerView,需要在四個方向上對其ItemDecoration進行限制,來看一下其實現類GridLayoutItemDecoration的getItemOffsets:

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    final int position = parent.getChildAdapterPosition(view);
    final int totalCount = parent.getAdapter().getItemCount();
    int left = (position % mSpanCount == 0) ? 0 : mHorizonSpan;
    int bottom = ((position + 1) % mSpanCount == 0) ? 0 : mVerticalSpan;
    if (isVertical(parent)) {
        if (!isLastRaw(parent, position, mSpanCount, totalCount)) {
            outRect.set(left, 0, 0, mVerticalSpan);
        } else {
            outRect.set(left, 0, 0, 0);
        }
    } else {
        if (!isLastColumn(parent, position, mSpanCount, totalCount)) {
            outRect.set(0, 0, mHorizonSpan, bottom);
        } else {
            outRect.set(0, 0, 0, bottom);
        }
    }
}

其實上面的代碼就是根據RecyclerView滑動方向(橫向或者縱向)以及child的位置(是不是最后一行或者最后一列),對附屬區域進行限制,同樣,如果不是特殊的分割線樣式,通過背景就基本可以實現需求,不用特殊draw。

全展開的列表式RecyclerView--ExpandedLinearLayoutManager

RecyclerView全展開的邏輯跟分割線不同,全展開主要是跟measure邏輯相關,簡單看一下RecyclerView(v-22版本,相對簡單)的measure源碼:

@Override
protected void onMeasure(int widthSpec, int heightSpec) {
        ...
        
        <!--關鍵代碼,如果mLayout(LayoutManager)非空,就采用LayoutManager的mLayout.onMeasure-->
    if (mLayout == null) {
        defaultOnMeasure(widthSpec, heightSpec);
    } else {
        mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
    }

    mState.mInPreLayout = false; // clear
}

由以上代碼可以看出,在為RecyclerView設置了LayoutManager之后,RecyclerView的measure邏輯其實就是委托給了它的LayoutManager,這里以LinearLayoutManager為例,不過LinearLayoutManager源碼里面并沒有重寫onMeasure函數,也就是說,對于RecyclerView的線性樣式,對于尺寸的處理采用的是跟ViewGroup一樣的處理,完全由父控件限制,不過對于v-23里面有了一些修改,就是增加了對wrap_content的支持。既然這樣,我們就可以把設置尺寸的時機放到LayoutManager的onMeasure中,對全展開的RecyclerView來說,其實就是將所有child測量一遍,之后將每個child需要高度或者寬度累加,看一下ExpandedLinearLayoutManager的實現:在測量child的時候,采用RecyclerView的measureChildWithMargins,該函數已經將ItemDecoration的占位考慮進去,之后通過getDecoratedMeasuredWidth獲取真正需要占用的尺寸。

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int measureWidth = 0;
    int measureHeight = 0;
    int count;
    if (mMaxItemCount < 0 || getItemCount() < mMaxItemCount) {
        count = getItemCount();
    } else {
        count = mMaxItemCount;
    }
    for (int i = 0; i < count; i++) {
        int[] measuredDimension = getChildDimension(recycler, i);
        if (measuredDimension == null || measuredDimension.length != 2)
            return;
        if (getOrientation() == HORIZONTAL) {
            measureWidth = measureWidth + measuredDimension[0];
           <!--獲取最大高度-->
            measureHeight = Math.max(measureHeight, measuredDimension[1]);
        } else {
            measureHeight = measureHeight + measuredDimension[1];
            <!--獲取最大寬度-->
            measureWidth = Math.max(measureWidth, measuredDimension[0]);
        }
    }

    measureHeight = heightMode == View.MeasureSpec.EXACTLY ? heightSize : measureHeight;
    measureWidth = widthMode == View.MeasureSpec.EXACTLY ? widthSize : measureWidth;
    if (getOrientation() == VERTICAL && measureWidth > widthSize) {
        measureWidth = widthSize;
    } else if (getOrientation() == HORIZONTAL && measureHeight > heightSize) {
        measureHeight = heightSize;
    }
    setMeasuredDimension(measureWidth, measureHeight);
}


private int[] getChildDimension(RecyclerView.Recycler recycler, int position) {
    try {
        int[] measuredDimension = new int[2];
        View view = recycler.getViewForPosition(position);
        //測量childView,以便獲得寬高(包括ItemDecoration的限制)
        super.measureChildWithMargins(view, 0, 0);
        //獲取childView,以便獲得寬高(包括ItemDecoration的限制),以及邊距
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
        measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
        return measuredDimension;
    } catch (Exception e) {
        Log.d("LayoutManager", e.toString());
    }
    return null;
}

全展開的網格式RecyclerView--ExpandedGridLayoutManager

全展開的網格式RecyclerView的實現跟線性的十分相似,唯一不同的就是在確定尺寸的時候,不是將每個child的尺寸疊加,而是要將每一行或者每一列的尺寸疊加,這里假定行高或者列寬都是相同的,其實在使用中這兩種場景也是最常見的,看如下代碼,其實除了加了行與列判斷邏輯,其他基本跟上面的全展開線性的類似。

 @Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int measureWidth = 0;
    int measureHeight = 0;
    int count = getItemCount();
    int span = getSpanCount();
    for (int i = 0; i < count; i++) {
        measuredDimension = getChildDimension(recycler, i);
        if (getOrientation() == HORIZONTAL) {
            if (i % span == 0 ) {
                measureWidth = measureWidth + measuredDimension[0];
            }
            measureHeight = Math.max(measureHeight, measuredDimension[1]);
        } else {
            if (i % span == 0) {
                measureHeight = measureHeight + measuredDimension[1];
            }
            measureWidth = Math.max(measureWidth, measuredDimension[0]);
        }
    }
    measureHeight = heightMode == View.MeasureSpec.EXACTLY ? heightSize : measureHeight;
    measureWidth = widthMode == View.MeasureSpec.EXACTLY ? widthSize : measureWidth;
    setMeasuredDimension(measureWidth, measureHeight);
}

最后附上橫向滑動效果圖:

橫向滑動

以上就是比較通用的RecyclerView使用場景及所做的兼容 ,最后附上Github鏈接RecyclerItemDecoration,歡迎star,fork。

作者:看書的小蝸牛
原文鏈接: RecyclerView定制:通用ItemDecoration及全展開RecyclerView的實現

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容