如何使用CocatAdapter在垂直Adapter中添加横向Adapter
你提到的CocatAdapter应为笔误,实际是Jetpack RecyclerView组件提供的ConcatAdapter,以下是具体实现步骤:
前置依赖
首先确保项目引入了支持ConcatAdapter的RecyclerView版本,在模块级build.gradle的dependencies中添加:
implementation "androidx.recyclerview:recyclerview:1.2.1" // 版本 >=1.2.0 即可支持ConcatAdapter
实现逻辑
整体实现思路是:垂直方向的主RecyclerView使用ConcatAdapter拼接多个子Adapter,其中专门有一个子Adapter对应横向列表区块,这个子Adapter的item内嵌横向RecyclerView,绑定你写好的横向Adapter即可。
具体操作步骤
- 第一步:实现横向列表的普通Adapter,和常规RecyclerView.Adapter写法完全一致,绑定横向列表的单个item布局、处理数据逻辑即可。
- 第二步:实现垂直主列表的其他业务Adapter,比如头部模块Adapter、普通垂直列表项Adapter,写法和常规Adapter无差异。
- 第三步:实现横向列表容器Adapter,这个Adapter只用来承载横向滑动的RecyclerView:
- 首先写该Adapter对应的item布局,布局内只有一个RecyclerView,设置orientation为horizontal:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/horizontal_rv" android:layout_width="match_parent" android:layout_height="120dp" android:orientation="horizontal" />- 在该Adapter的
onCreateViewHolder方法中,初始化上述横向RecyclerView,给它设置水平布局管理器,再绑定你第一步写好的横向Adapter:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_horizontal_container, parent, false) val horizontalRv = view.findViewById<RecyclerView>(R.id.horizontal_rv) horizontalRv.layoutManager = LinearLayoutManager(parent.context, LinearLayoutManager.HORIZONTAL, false) horizontalRv.adapter = yourHorizontalAdapter // 替换为你自己的横向Adapter实例 return ViewHolder(view) }- 该Adapter的getItemCount固定返回1即可,因为整个横向列表只占主垂直列表的一个item位置。
- 第四步:组装ConcatAdapter,设置给主垂直RecyclerView:
- 先给主RecyclerView设置垂直布局管理器:
mainRv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)- 按你需要的展示顺序,把所有子Adapter传入ConcatAdapter构造方法,比如顺序是「头部Adapter→横向列表容器Adapter→普通垂直列表Adapter」:
val concatAdapter = ConcatAdapter(headerAdapter, horizontalContainerAdapter, normalVerticalAdapter)- 把ConcatAdapter设置给主RecyclerView即可:
mainRv.adapter = concatAdapter
注意事项
- 如果多个子Adapter存在相同的viewType,需要给ConcatAdapter配置隔离参数,避免渲染异常:
val config = ConcatAdapter.Config.Builder() .setIsolateViewTypes(true) // 开启后不同子Adapter的viewType会自动隔离,不会冲突 .build() val concatAdapter = ConcatAdapter(config, adapter1, adapter2, adapter3) - 横向RecyclerView的高度需要固定或者自适应内容,不要设置为match_parent,避免占满主列表的整个高度。
- 不需要给横向RecyclerView套NestedScrollView,直接在容器Adapter里设置固定高度即可保证横向滑动和item复用逻辑正常。
内容的提问来源于stack exchange,提问作者Nicote Ool
相关产品推荐
相关产品推荐

