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

Android Fragment中RecyclerView显示为空问题求助

问题分析与修复

核心问题:重复初始化ViewBinding

你在onCreateView里做了两次FragmentAppBinding.inflate:

  1. 第一次binding = FragmentAppBinding.inflate(inflater, container, false);已经正确绑定了Fragment要显示的视图,并且拿到了root准备返回。
  2. 但紧接着又执行了binding = FragmentAppBinding.inflate(getLayoutInflater());,这会创建一个新的、未关联到当前Fragment容器的Binding实例。后续你操作的binding.studentsRecyclerView属于这个新实例,而它根本没被添加到界面上,所以RecyclerView自然显示为空。

其他小问题

  • 设置Adapter时写错了变量名:binding.studentsRecyclerView.setAdapter(StudentAdapter);应该是studentAdapter(小写开头的对象名,不是类名),否则会编译报错。
  • Context获取可以直接用requireContext(),比container.getContext()更稳妥,避免容器为空的情况。
  • 异常处理里直接抛出RuntimeException会导致App崩溃,建议改成Toast提示或者日志打印。

修复后的代码

public class MyFragment extends Fragment { // 修正类名拼写错误(原MyFragement少了一个r)

private FragmentAppBinding binding;

@Override
public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    // 只做一次正确的Binding初始化
    binding = FragmentAppBinding.inflate(inflater, container, false);
    View root = binding.getRoot();

    String url = "https://server.com/users/api.json";
    ArrayList<FetchStudentModel> studentList = new ArrayList<>(); // 变量名更符合规范

    StringRequest request = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONArray jsonArray = new JSONArray(response);
                // 保留原逻辑,跳过第一个对象
                JSONObject checkLastUpdate = jsonArray.getJSONObject(0);

                for (int i = 1; i < jsonArray.length(); i++) {
                    JSONObject singleStudent = jsonArray.getJSONObject(i);
                    int id = singleStudent.getInt("id");
                    String name = singleStudent.getString("student_name");
                    studentList.add(new FetchStudentModel(id, name));
                }

                // 正确设置RecyclerView,注意变量名是studentAdapter
                StudentAdapter studentAdapter = new StudentAdapter(studentList, requireContext());
                binding.studentsRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
                binding.studentsRecyclerView.setAdapter(studentAdapter);

            } catch (JSONException e) {
                // 改成友好提示+日志记录
                Toast.makeText(requireContext(), "数据解析失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            String errorMsg = error.getMessage() != null ? error.getMessage() : "未知错误";
            Toast.makeText(requireContext(), "请求失败:" + errorMsg, Toast.LENGTH_SHORT).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(requireContext());
    requestQueue.add(request);

    return root;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    // 无需手动置空Adapter,直接释放Binding即可
    binding = null;
}
}

额外建议

  • 类名和变量名尽量遵循Java规范(小驼峰/大驼峰),比如FetchStudentModelArrayList改成studentList更易读。
  • 网络请求建议放在ViewModel中,避免Fragment重建时重复请求数据,也更符合Android架构最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:25:20