【Android】自定義無限循環(huán)的LayoutManager

概述

在日常開發(fā)的過程中,同學們都遇到過需要RecyclerView無限循環(huán)的需求,但是在官方提供的幾種LayoutManager中并未支持無限循環(huán)。

遇到此種問題,通常的解決方案是:

1、在adapter返回Integer.MAX_VALUE并讓RecyclerView滑動到某個足夠大的位置。

2、選擇自定義LayoutManager,實現(xiàn)循環(huán)的RecyclerView。

自定義LayoutManager的難度較高,本文將帶大家一起實現(xiàn)這個自定義LayoutManager,效果如下圖所示。同時,在熟悉了在自定義LayoutManager后,還可以根據(jù)需要調整RecyclerView的展示效果。

image

image

初探LayoutManager

自定義ViewGroup類似,自定義LayoutManager所要做的就是ItemView的「添加(add)」、「測量(measure)」、「布局(layout)」。

但是自定義ViewGroup相比,LayoutManager多了一個「回收(recycle)」工作。

在自定義LayoutManager之前,需要對其提供的「測量」、「布局」以及「回收」相關的API進行了解。

measure

首先介紹測量方法,與自定義ViewGroup類似,測量通常是固定的邏輯不需要自己實現(xiàn),開發(fā)者無需復寫測量方法,只需要在布局之前調用測量函數(shù)來獲取將要布局的「View的寬度」即可。

LayoutManager提供了兩個用來測量子View的方法:

//測量子View
public void measureChild(@NonNull View child, int widthUsed, int heightUsed)

//測量子View,并將子View的Margin也考慮進來,通常使用此函數(shù)
public void measureChildWithMargins(@NonNull View child, int widthUsed, int heightUsed)

測量完成后,便可以使用getMeasuredWidth()、getMeasuredHeight()直接獲取View的寬高,但是在自定義LayoutManager中需要考慮ItemDecoration,所以需要通過如下兩個API獲取測量后的View大小:

//獲取child的寬度,并將ItemDecoration考慮進來
public int getDecoratedMeasuredWidth(@NonNull View child) {
    final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
    return child.getMeasuredWidth() + insets.left + insets.right;
}
//獲取child的高度,并將ItemDecoration考慮進來
public int getDecoratedMeasuredHeight(@NonNull View child) {
    final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
    return child.getMeasuredHeight() + insets.top + insets.bottom;
}

layout

然后介紹layout方法,和自定義ViewGroup一樣,LayoutManager完成ItemView的測量后就是布局了。

LayoutManager中,并非靠直接調用ItemView的layout函數(shù)進行子View的布局,而是使用layoutDecoratedlayoutDecoratedWithMargins, 兩者的區(qū)別是后者考慮了Margins:

public void layoutDecorated(@NonNull View child, int left, int top, int right, int bottom) {
    final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
    child.layout(left + insets.left, top + insets.top, right - insets.right,
                bottom - insets.bottom);
}

public void layoutDecoratedWithMargins(@NonNull View child, int left, int top, int right,
                int bottom) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    final Rect insets = lp.mDecorInsets;
    child.layout(left + insets.left + lp.leftMargin, top + insets.top + lp.topMargin,
            right - insets.right - lp.rightMargin,
            bottom - insets.bottom - lp.bottomMargin);
}

recycle

回收是RecyclerView的靈魂,也是RecyclerView與普通ViewGroup的區(qū)別。眾所周知,RecyclerView中含有四類緩存,在布局過程中它們各自有各自的用途:

1、AttachedScrap: 存放可見、不需要重新綁定的ViewHolder

2、CachedViews: 存放不可見、不需要重新綁定的ViewHoler

3、ViewCacheExtension: 自定義緩存(存放不可見、不需要重新綁定)

4、RecyclerPool: 存放不可見、需要重新綁定的ViewHolder

<div align="center">
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c9bd6e9d70b841699dbdd600e7c1fc1d~tplv-k3u1fbpfcp-watermark.image" width = "600" height = "400" alt="1xx"/>
</div>

LayoutManager中提供了多個回收方法:

//將指定的View直接回收加至ecyclerPool
public void removeAndRecycleView(@NonNull View child, @NonNull Recycler recycler) {
    removeView(child);
    recycler.recycleView(child);
}
//將指定位置的View直接回收加至ecyclerPool
public void removeAndRecycleViewAt(int index, @NonNull Recycler recycler) {
    final View view = getChildAt(index);
    removeViewAt(index);
    recycler.recycleView(view);
}

LayoutManager創(chuàng)建

1、實現(xiàn)抽抽象方法,并讓RecyclerView可橫向滑動

public class RepeatLayoutManager extends RecyclerView.LayoutManager {
    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public boolean canScrollHorizontally() {
        return true;
    }
}

2、定義初始布局

onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)方法中對ItemView進行添加、測量、布局。

具體步驟如下:

  • 使用recycler.getViewForPosition(int pos)從緩存中獲取子View
  • 當可布局區(qū)域有多余的空間時,通過addView(View view)將對子View進行添加,通過在RecyclerView中添加子View,并對子View進行測量與布局,直至子View超出RecyclerView的可布局寬度。
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() <= 0) {
            return;
        }
        if (state.isPreLayout()) {
            return;
        }
        //將所有Item分離至scrap
        detachAndScrapAttachedViews(recycler);
        int itemLeft = getPaddingLeft();
        for (int i = 0; ; i++) {
            if (itemLeft >= getWidth() - getPaddingRight()) {
                break;
            }
            View itemView = recycler.getViewForPosition(i % getItemCount());
            //添加子View
            addView(itemView);
            //測量子View
            measureChildWithMargins(itemView, 0, 0);

            int right = itemLeft + getDecoratedMeasuredWidth(itemView);
            int top = getPaddingTop();
            int bottom = top + getDecoratedMeasuredHeight(itemView) - getPaddingBottom();
            //對子View進行布局
            layoutDecorated(itemView, itemLeft, top, right, bottom);
            itemLeft = right;
        }
    }

3、滑動與填充

offsetChildrenHorizontal(int x)用作對RecyclerView中的子View進行整體左右移動。
為了在滑動RecyclerView時有子View移動的效果,需要復寫scrollHorizontallyBy函數(shù),并在其中調用offsetChildrenHorizontal(int x)。

當左滑后子View被左移動時,RecyclerView的右側會出現(xiàn)可見的未填充區(qū)域,這時需要在RecyclerView右側添加并布局好新的子View,直到?jīng)]有可見的未填充區(qū)域為止。

image

同樣,在右滑后需要對左側的未填充區(qū)域進行填充。

具體代碼如下:

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        fill(recycler, dx > 0);
        offsetChildrenHorizontal(-dx);
        return dx;
    }
    
    /**
     * 滑動的時候,填充可見的未填充區(qū)域
     */
    private void fill(RecyclerView.Recycler recycler, boolean fillEnd) {
        if (getChildCount() == 0) return;
        if (fillEnd) {
            //填充尾部
            View anchorView = getChildAt(getChildCount() - 1);
            int anchorPosition = getPosition(anchorView);
            for (; anchorView.getRight() < getWidth() - getPaddingRight(); ) {
                int position = (anchorPosition + 1) % getItemCount();
                if (position < 0) position += getItemCount();

                View scrapItem = recycler.getViewForPosition(position);
                addView(scrapItem);
                measureChildWithMargins(scrapItem, 0, 0);
                
                int left = anchorView.getRight();
                int top = getPaddingTop();
                int right = left + getDecoratedMeasuredWidth(scrapItem);
                int bottom = top + getDecoratedMeasuredHeight(scrapItem) - getPaddingBottom();
                layoutDecorated(scrapItem, left, top, right, bottom);
                anchorView = scrapItem;
            }
        } else {
            //填充首部
            View anchorView = getChildAt(0);
            int anchorPosition = getPosition(anchorView);
            for (; anchorView.getLeft() > getPaddingLeft(); ) {
                int position = (anchorPosition - 1) % getItemCount();
                if (position < 0) position += getItemCount();

                View scrapItem = recycler.getViewForPosition(position);
                addView(scrapItem, 0);
                measureChildWithMargins(scrapItem, 0, 0);
                int right = anchorView.getLeft();
                int top = getPaddingTop();
                int left = right - getDecoratedMeasuredWidth(scrapItem);
                int bottom = top + getDecoratedMeasuredHeight(scrapItem) - getPaddingBottom();
                layoutDecorated(scrapItem, left, top,
                        right, bottom);
                anchorView = scrapItem;
            }
        }
        return;
    }

回收

前面講到,當對RecyclerView進行滑動時,需要對可見的未填充區(qū)域進行填充。然而一直填充不做回收Item,那就和普通的ViewGroup沒有太多的區(qū)別了。

RecyclerView中,需要在滑動、填充可見區(qū)域的同時,對不可見區(qū)域的子View進行回收,這樣才能體現(xiàn)出RecyclerView的優(yōu)勢。

回收的方向與填充的方向恰好相反。那回收的代碼具體如何實現(xiàn)呢?代碼如下:

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        fill(recycler, dx > 0);
        offsetChildrenHorizontal(-dx);
        recyclerChildView(dx > 0, recycler);
        return dx;
    }
    
    /**
     * 回收不可見的子View
     */
    private void recyclerChildView(boolean fillEnd, RecyclerView.Recycler recycler) {
        if (fillEnd) {
            //回收頭部
            for (int i = 0; ; i++) {
                View view = getChildAt(i);
                boolean needRecycler = view != null && view.getRight() < getPaddingLeft();
                if (needRecycler) {
                    removeAndRecycleView(view, recycler);
                } else {
                    return;
                }
            }
        } else {
            //回收尾部
            for (int i = getChildCount() - 1; ; i--) {
                View view = getChildAt(i);
                boolean needRecycler = view != null && view.getLeft() > getWidth() - getPaddingRight();
                if (needRecycler) {
                    removeAndRecycleView(view, recycler);
                } else {
                    return;
                }
            }
        }
    }

使用

  • 添加依賴
 implementation 'cn.student0.manager:repeatmanager:1.0.2'
  • 在代碼中使用
  RecyclerView recyclerView = findViewById(R.id.rv_demo);
  recyclerView.setAdapter(new DemoAdapter());
  recyclerView.setLayoutManager(new RepeatLayoutManager

結語

到此,無限循環(huán)的LayoutManager的實現(xiàn)已經(jīng)完成。文章的不足還請指出,謝謝大家。

Github地址:https://github.com/jiarWang/RepeatLayoutManager, 歡迎大家Star。
感謝HenCoder團隊

參考

Android自定義LayoutManager第十一式之飛龍在天

【Android】掌握自定義LayoutManager(一) 系列開篇 常見誤區(qū)、問題、注意事項,常用API

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

相關閱讀更多精彩內容

友情鏈接更多精彩內容