
相信大家基本都遇到過類似京東的評價列表的這種需求,具體的實(shí)現(xiàn)邏輯是RecyclerView 嵌套RecyclerView 來實(shí)現(xiàn)的,那么我們?nèi)绾蝸硖嵘男阅苣?又如何使用最少的代碼來達(dá)到我們想要的效果呢,下面我們來分析一下,
1.想要實(shí)現(xiàn)上面的效果,內(nèi)部的RecyclerView 的LayoutManager 必須是GridLayoutManager ,我們根據(jù)數(shù)據(jù)的個數(shù)來設(shè)置spancount,從而來達(dá)到
2.外層的RecyclerView 會根據(jù)自身來緩存view 的信息,從而來提升渲染速度,難么嵌套在內(nèi)部的RecyclerView 如何來緩存呢, 答案就是使用 RecyclerView.RecycledViewPool ,所有的內(nèi)部RecyclerView 來共享一個RecyclerView 的第四極緩存 ,如果對換粗機(jī)制不了解的可以看一下這篇文章(RecyclerView 學(xué)習(xí) (二) 關(guān)于RecyclerView 緩存機(jī)制 http://www.itdecent.cn/p/4c6affc0c4cf ),這樣就保證在內(nèi)部RecyclerView 的item被回收時,會將所有item 放入到這個RecyclerView.RecycledViewPool,查看RecyclerView.RecycledViewPool 的源碼我們發(fā)現(xiàn) RecyclerView.RecycledViewPool是有上限的,那么我么如何來設(shè)置他的上限呢,其實(shí)可以參照 RecyclerView 自身的二級緩存,也就是2個item,這里可以看成內(nèi)部RecyclerView 的2倍的最大個數(shù) 也就是6
3.想要實(shí)現(xiàn)2中思想在給內(nèi)部RecyclerView設(shè)置屬性時,需要編寫大量的代碼,我們?nèi)绾蝸頊p少代碼的書寫呢
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_top_desc"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:focusable="false"
android:layout_marginBottom="12dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@id/pic_item_designer_header"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="3"
tools:listitem="@layout/item_designer_desc_str"
android:layout_marginRight="8dp"
tools:itemCount="3"/>
注意,我在編寫內(nèi)部RecyclerView 時,指定了他的 layoutManager 為GridLayoutManager,那么在 外部adapter的時候就可以簡寫為
helper?.getView<RecyclerView>(R.id.recycler_view_top_desc)?.let {
it.setRecycledViewPool(pools)
var layoutManager= it.layoutManager as GridLayoutManager
layoutManager.spanCount=item?.designerTags?.size?:1
if(it.adapter==null){
it.adapter=DesignerStarDescAdapter(null)
}
(it.adapter as DesignerStarDescAdapter)?.apply {
setNewData(item?.designerTags)
setOnItemClickListener { adapter, view, position ->
this@DesignerStartListAdapter.onItemClickListener.onItemClick(this@DesignerStartListAdapter,helper.itemView,helper?.adapterPosition)
}
}
}
這樣看起來是不是非常簡單明了,而且還做到了layoutManager 的復(fù)用,不用增加額外的判斷