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

Android Fragment中RecyclerView不显示,ArrayList非空如何排查解决?

问题根因

  • 你在Fragment初始化控件时错误使用getActivity().findViewById()查找控件,这个方法是从宿主Activity的布局树找控件,而不是从当前Fragment自己加载的布局里找,导致你拿到的RecyclerView实例其实为空,或者拿到的是其他页面的RecyclerView,自然无法正常渲染内容。
  • 另外onActivityCreated已经被官方废弃,推荐把初始化逻辑放到onViewCreated里执行,更符合Fragment的生命周期规范。

修复步骤

  1. 先修改onCreateView,保存你inflate出来的Fragment根视图实例:
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // 保存当前Fragment的根视图
    rootView = inflater.inflate(R.layout.fragment_home_skills, container, false);
    return rootView;
}
  1. 删掉原来onActivityCreated里的所有逻辑,重写onViewCreated方法,用刚才保存的rootView查找控件:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    bottomNavigationVisibility = new BottomNavigationVisibility(getActivity());
    bottomNavigationVisibility.hideBottomNavigation();

    // 从Fragment自己的根视图查找控件,不要使用getActivity
    Search = rootView.findViewById(R.id.search_editText);
    back = rootView.findViewById(R.id.back);
    recyclerView = rootView.findViewById(R.id.recyclerView);
    gridLayoutManager = new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false);
    recyclerView.setLayoutManager(gridLayoutManager);

    // 其余原有逻辑保持不变,包括getDataFromDB、返回键点击事件等
    getDataFromDB();

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomNavigationVisibility.showBottomNavigation();
            NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
            navController.navigate(R.id.navigation_home);
        }
    });
}
  1. 可选优化:你现在每次数据库回调都重新创建Adapter,建议提前初始化Adapter,后续数据变化时调用adapter.notifyDataSetChanged()更新即可,性能更好:
// 控件初始化完成后就提前初始化Adapter
postItem = new ArrayList<>();
adapter = new postAdapter(getContext(),postItem);
recyclerView.setAdapter(adapter);

// 数据库回调里添加完数据直接通知更新即可
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        postItem.clear();
        for(DataSnapshot dataSnapshot: snapshot.getChildren()){
            Post post = dataSnapshot.getValue(Post.class);
            if(post.getCategory().equals("Skills, M" ) || post.getCategory().equals("Skills, S"))
                postItem.add(post);
        }
        adapter.notifyDataSetChanged();
    }
    // 原有onCancelled逻辑保持不变
    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Toast.makeText(getContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:01