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

如何在Fragment中向LinearLayout添加View?空引用问题求解

解决Fragment中添加View时的空引用异常

问题原因

你代码里通过inflater.inflate(R.layout.fragment_manager, ...)加载的布局文件,和你提供的包含buttons LinearLayout的XML布局不匹配,导致rootView.findViewById(R.id.buttons)返回null,调用layout.addView()时触发空引用异常。

解决方案

  • 修正布局加载ID:确认你inflate的布局ID对应正确的XML文件。比如如果目标XML文件名是fragment_buttons.xml,将代码中的布局ID改为R.layout.fragment_buttons。
  • 清理重建项目:若ID确认无误仍报错,执行Android Studio的Clean Project和Rebuild Project操作,确保R文件同步更新。
  • 检查控件ID拼写:核对XML中android:id="@+id/buttons"和代码中R.id.buttons的拼写完全一致,无大小写或字符错误。

修正后的示例代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // 替换为对应XML的正确布局ID
    rootView = inflater.inflate(R.layout.fragment_buttons, container, false);

    LinearLayout layout = rootView.findViewById(R.id.buttons);
    // 增加非空判断,避免潜在异常
    if (layout != null) {
        TextView test = new TextView(getContext());
        test.setText("Test");
        layout.addView(test);
    }

    return rootView;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:12:12