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

概述

在日常開(kāi)發(fā)的過(guò)程中,同學(xué)們都遇到過(guò)需要RecyclerView無(wú)限循環(huán)的需求谴麦,但是在官方提供的幾種LayoutManager中并未支持無(wú)限循環(huán)捧书。

遇到此種問(wèn)題稼跳,通常的解決方案是:

1、在adapter返回Integer.MAX_VALUE并讓RecyclerView滑動(dòng)到某個(gè)足夠大的位置阶剑。

2跃巡、選擇自定義LayoutManager,實(shí)現(xiàn)循環(huán)的RecyclerView牧愁。

自定義LayoutManager的難度較高素邪,本文將帶大家一起實(shí)現(xiàn)這個(gè)自定義LayoutManager,效果如下圖所示猪半。同時(shí)兔朦,在熟悉了在自定義LayoutManager后,還可以根據(jù)需要調(diào)整RecyclerView的展示效果磨确。

image

image

初探LayoutManager

自定義ViewGroup類(lèi)似烘绽,自定義LayoutManager所要做的就是ItemView的「添加(add)」、「測(cè)量(measure)」俐填、「布局(layout)」安接。

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

在自定義LayoutManager之前盏檐,需要對(duì)其提供的「測(cè)量」、「布局」以及「回收」相關(guān)的API進(jìn)行了解驶悟。

measure

首先介紹測(cè)量方法胡野,與自定義ViewGroup類(lèi)似,測(cè)量通常是固定的邏輯不需要自己實(shí)現(xiàn)痕鳍,開(kāi)發(fā)者無(wú)需復(fù)寫(xiě)測(cè)量方法硫豆,只需要在布局之前調(diào)用測(cè)量函數(shù)來(lái)獲取將要布局的「View的寬度」即可。

LayoutManager提供了兩個(gè)用來(lái)測(cè)量子View的方法:

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

//測(cè)量子View笼呆,并將子View的Margin也考慮進(jìn)來(lái)熊响,通常使用此函數(shù)
public void measureChildWithMargins(@NonNull View child, int widthUsed, int heightUsed)

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

//獲取child的寬度,并將ItemDecoration考慮進(jìn)來(lái)
public int getDecoratedMeasuredWidth(@NonNull View child) {
    final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
    return child.getMeasuredWidth() + insets.left + insets.right;
}
//獲取child的高度铭若,并將ItemDecoration考慮進(jìn)來(lái)
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的測(cè)量后就是布局了。

LayoutManager中瞳腌,并非靠直接調(diào)用ItemView的layout函數(shù)進(jìn)行子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中含有四類(lèi)緩存,在布局過(guò)程中它們各自有各自的用途:

1吵冒、AttachedScrap: 存放可見(jiàn)、不需要重新綁定的ViewHolder

2西剥、CachedViews: 存放不可見(jiàn)痹栖、不需要重新綁定的ViewHoler

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

4揪阿、RecyclerPool: 存放不可見(jiàn)、需要重新綁定的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中提供了多個(gè)回收方法:

//將指定的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咆畏、實(shí)現(xiàn)抽抽象方法南捂,并讓RecyclerView可橫向滑動(dòng)

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)方法中對(duì)ItemView進(jìn)行添加旧找、測(cè)量溺健、布局。

具體步驟如下:

  • 使用recycler.getViewForPosition(int pos)從緩存中獲取子View
  • 當(dāng)可布局區(qū)域有多余的空間時(shí),通過(guò)addView(View view)將對(duì)子View進(jìn)行添加钮蛛,通過(guò)在RecyclerView中添加子View,并對(duì)子View進(jìn)行測(cè)量與布局鞭缭,直至子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);
            //測(cè)量子View
            measureChildWithMargins(itemView, 0, 0);

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

3魏颓、滑動(dòng)與填充

offsetChildrenHorizontal(int x)用作對(duì)RecyclerView中的子View進(jìn)行整體左右移動(dòng)岭辣。
為了在滑動(dòng)RecyclerView時(shí)有子View移動(dòng)的效果,需要復(fù)寫(xiě)scrollHorizontallyBy函數(shù)甸饱,并在其中調(diào)用offsetChildrenHorizontal(int x)沦童。

當(dāng)左滑后子View被左移動(dòng)時(shí),RecyclerView的右側(cè)會(huì)出現(xiàn)可見(jiàn)的未填充區(qū)域叹话,這時(shí)需要在RecyclerView右側(cè)添加并布局好新的子View偷遗,直到?jīng)]有可見(jiàn)的未填充區(qū)域?yàn)橹埂?br>

image

同樣,在右滑后需要對(duì)左側(cè)的未填充區(qū)域進(jìn)行填充驼壶。

具體代碼如下:

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        fill(recycler, dx > 0);
        offsetChildrenHorizontal(-dx)鹦肿;
        return dx;
    }
    
    /**
     * 滑動(dòng)的時(shí)候,填充可見(jiàn)的未填充區(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;
    }

回收

前面講到辅柴,當(dāng)對(duì)RecyclerView進(jìn)行滑動(dòng)時(shí)箩溃,需要對(duì)可見(jiàn)的未填充區(qū)域進(jìn)行填充瞭吃。然而一直填充不做回收Item,那就和普通的ViewGroup沒(méi)有太多的區(qū)別了涣旨。

RecyclerView中歪架,需要在滑動(dòng)、填充可見(jiàn)區(qū)域的同時(shí)霹陡,對(duì)不可見(jiàn)區(qū)域的子View進(jìn)行回收和蚪,這樣才能體現(xiàn)出RecyclerView的優(yōu)勢(shì)。

回收的方向與填充的方向恰好相反烹棉。那回收的代碼具體如何實(shí)現(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;
    }
    
    /**
     * 回收不可見(jiàn)的子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

結(jié)語(yǔ)

到此,無(wú)限循環(huán)的LayoutManager的實(shí)現(xiàn)已經(jīng)完成浆洗。文章的不足還請(qǐng)指出催束,謝謝大家。

Github地址:https://github.com/jiarWang/RepeatLayoutManager, 歡迎大家Star伏社。
感謝HenCoder團(tuán)隊(duì)

參考

Android自定義LayoutManager第十一式之飛龍?jiān)谔?/a>

【Android】掌握自定義LayoutManager(一) 系列開(kāi)篇 常見(jiàn)誤區(qū)抠刺、問(wèn)題、注意事項(xiàng)摘昌,常用API

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末速妖,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子聪黎,更是在濱河造成了極大的恐慌罕容,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件稿饰,死亡現(xiàn)場(chǎng)離奇詭異杀赢,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)湘纵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)脂崔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人梧喷,你說(shuō)我怎么就攤上這事砌左。” “怎么了铺敌?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵汇歹,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我偿凭,道長(zhǎng)产弹,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮痰哨,結(jié)果婚禮上胶果,老公的妹妹穿的比我還像新娘。我一直安慰自己斤斧,他們只是感情好早抠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著撬讽,像睡著了一般蕊连。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上游昼,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天甘苍,我揣著相機(jī)與錄音,去河邊找鬼烘豌。 笑死载庭,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的扇谣。 我是一名探鬼主播昧捷,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼闲昭,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼罐寨!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起序矩,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤鸯绿,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后簸淀,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體瓶蝴,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年租幕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了舷手。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡劲绪,死狀恐怖男窟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贾富,我是刑警寧澤歉眷,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站颤枪,受9級(jí)特大地震影響汗捡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜畏纲,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一扇住、第九天 我趴在偏房一處隱蔽的房頂上張望春缕。 院中可真熱鬧,春花似錦台囱、人聲如沸淡溯。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)咱娶。三九已至,卻和暖如春强品,著一層夾襖步出監(jiān)牢的瞬間膘侮,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工的榛, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留琼了,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓夫晌,卻偏偏與公主長(zhǎng)得像雕薪,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子晓淀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容