SectionedRecyclerViewAdapter废弃getItemViewType,如何获取视图类型
SectionedRecyclerViewAdapter场景下替换废弃getItemViewType实现跨度设置的方案
废弃提示触发原因
在AndroidX RecyclerView 1.3.0及以上版本中,从外部跨类调用Adapter实例的getItemViewType(int position)方法会被标记为废弃。核心原因是该方法原本设计为Adapter内部onCreateViewHolder流程调用的接口,外部直接调用会绕开Adapter内部的视图类型映射逻辑(尤其是带分组、多视图类型自定义的Adapter),容易出现取值偏差。
适配SectionedRecyclerViewAdapter的替代方案
你当前使用的Adapter继承自SectionedRecyclerViewAdapter,不需要调用废弃的getItemViewType方法,可直接使用适配器为分组场景封装的公开方法安全获取指定位置的视图类型:
- 优先调用适配器实例的
getSectionItemViewType(int position)方法,该方法是SectionedRecyclerViewAdapter专门对外提供的位置视图类型获取接口,无废弃警告 - 如果当前依赖的SectionedRecyclerViewAdapter版本没有直接提供上述方法,可先通过
getSectionForPosition(int position)方法拿到目标位置对应的分组实例,再调用分组自身的getViewType()方法获取视图类型,该调用链同样不会触发废弃提示
修改后可正常运行的代码示例
MyAdapter myAdapter = new MyAdapter(this, items); this.myRecyclerView.setAdapter(myAdapter); GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // 替换原废弃的 myAdapter.getItemViewType(position) 调用 int viewType = myAdapter.getSectionItemViewType(position); switch (viewType) { case -1: // 普通列表项:占1列跨度 return 1; default: // 头部/分组项:占2列满跨度 return 2; } } }); this.myRecyclerView.setLayoutManager(layoutManager);
补充说明
- 这种获取方式可以兼容SectionedRecyclerViewAdapter内部对视图类型的自动偏移逻辑,不会因为分组数量增加出现视图类型取值错乱的问题
- 后续你需要将硬编码的视图类型值替换为枚举时,直接在获取到
viewType变量后对接枚举映射逻辑即可,不需要调整SpanSizeLookup的整体结构
内容的提问来源于stack exchange,提问作者Martin Braun
相关产品推荐
相关产品推荐

