You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fragment内RecyclerView未调用Adapter重写方法问题排查

RecyclerView Adapter方法未执行的问题排查与解决

问题描述

在Fragment中实现两个RecyclerView,其中用于地图展示的RecyclerView对应的MapAdapter重写方法从未执行。已确认:

  • getItemCount返回的条目数不为零(30*10=300)
  • 已为RecyclerView设置Adapter
  • 已为RecyclerView设置LayoutManager

核心问题与修复方案

1. ViewHolder中尺寸修改时机错误

在MapViewHolder构造方法中调用parent.getMeasuredHeight()时,View尚未完成测量流程,返回值为0,导致计算出的item宽高无效,进而RecyclerView无法正确布局item,最终不触发Adapter的生命周期方法。

修复代码:
将尺寸调整逻辑移至布局完成后执行:

public class MapViewHolder extends RecyclerView.ViewHolder {

    ImageView cellOne, cellTwo, cellThree, cellFour, structure;
    ConstraintLayout parent;

    public MapViewHolder(@NonNull View itemView) {
        super(itemView);
        cellOne = itemView.findViewById(R.id.imageOne);
        cellTwo = itemView.findViewById(R.id.imageTwo);
        cellThree = itemView.findViewById(R.id.imageThree);
        cellFour = itemView.findViewById(R.id.imageFour);
        parent = itemView.findViewById(R.id.parent);

        // 监听布局完成事件,确保测量完成后设置尺寸
        parent.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                // 移除监听器避免重复执行
                parent.removeOnLayoutChangeListener(this);
                int size = parent.getHeight() / MapData.HEIGHT;
                ViewGroup.LayoutParams lp = itemView.getLayoutParams();
                if (lp == null) {
                    lp = new ViewGroup.LayoutParams(size, size);
                } else {
                    lp.width = size;
                    lp.height = size;
                }
                itemView.setLayoutParams(lp);
            }
        });
    }
}

2. GridLayoutManager与RecyclerView布局参数不匹配

你设置的GridLayoutManager为水平方向,spanCount设为MapData.HEIGHT(10),意味着垂直方向会排列10个item。如果fragment_map.xml中mapRecyclerView的高度设置为wrap_content,水平方向的GridLayoutManager无法正确计算所需高度,导致RecyclerView没有足够空间展示内容,Adapter方法不会被触发。

修复方案:
修改fragment_map.xml中mapRecyclerView的布局参数,将高度设置为match_parent或固定值,例如:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/mapRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <!-- 其他属性 -->
/>

3. 额外验证点

  • 确认mapData对象不为null:在FragmentMap的onCreateView中添加日志验证
    Log.d("FragmentMap", "mapData是否为空: " + (mapData == null));
    
  • 检查mapRecyclerView是否被遮挡或设置为visibility="gone",确保其可见
  • 验证MapData.get(row, col)方法不会抛出异常,避免Adapter执行时崩溃被吞

内容的提问来源于stack exchange,提问作者evie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:54:33