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

Android Studio中Fragment初始化TextView时App崩溃问题求解

问题根源

你的空指针崩溃完全是initWidgets()方法写法错误导致的:
你定义的全局变量testTV默认初始值是null,结果方法里写的是testTV = testTV.findViewById(R.id.text_gallery)——相当于对着空对象调用方法,和Logcat里报的Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference完全对应。
这里有两个常识性错误:

  • findViewById()是View类的方法,必须在已经成功inflate的布局根View、或者已初始化的ViewBinding实例上调用,不能在还没赋值、为null的控件变量自身上调用。
  • 你这个项目已经启用了ViewBinding,根本不需要手动调用findViewById找控件,模板生成的代码里已经有binding.textGallery这个现成的TextView实例,重复写findViewById纯属多此一举。
修复方法

直接删掉没用的testTV全局变量、删掉整个initWidgets()方法即可,需要操作控件的时候直接用binding实例拿,修改后的核心代码如下:

public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);

        binding = FragmentGalleryBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textGallery;
        galleryViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 直接通过binding拿到TextView实例操作
        binding.textGallery.setText("Hello");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

如果你非要坚持手动写findViewById(非常不推荐,浪费代码还容易出问题),就把initWidgets方法改成接收布局根View作为参数,在传入的根View上调用findViewById:

public void initWidgets(View rootView){
   testTV = rootView.findViewById(R.id.text_gallery);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    initWidgets(view); // 把onViewCreated返回的布局根view传进去
    testTV.setText("Hello");
}

补充说明:Android Studio生成的Navigation Drawer模板默认已经配置好ViewBinding,xml里的控件只要加了id,就会自动生成小驼峰命名的binding引用,比如id为text_gallery的控件对应binding.textGallery,直接用就行,不用自己写findViewById。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 02:48:32