[Android踩坑] Fragment findViewById爲null

Fragment findViewByIdnull!!!

太久沒寫安卓了,連基礎的東西都忘記了,想在一個fragment裏寫一個RecycleView,
在寫以下這條語句時報錯
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
一開始以爲是LayoutManger的問題,怎麼查都不是,
getView.findViewById
getContext.findViewById
getActivity.findViewById
怎麼寫都報錯,
最後定眼一看,recycleView都是null ,我暈了,問題都找錯了。

我最開始 recycleView直接寫成 getView.findViewById。還是沒理解fragment的機制
以下是正確的過程,這纔是一個fragment裏寫出recycleView的簡要 過程。

 		View view = inflater.inflate(R.layout.fragment_detail, container, false);
        detailrecyclerView = view.findViewById(R.id.recycleViewDetail);
        detailFragmentAdapter = new DetailFragmentAdapter();
        detailrecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        detailrecyclerView.setAdapter(detailFragmentAdapter);

這就涉及到有關Fragment的getActivity().findViewById,以及inflate與 findViewById 區別、setContentView和inflate的區別!!!
直接附上好文!詳細解讀

【Fragment精深系列5】fragment findViewById()返回null完全解析
https://blog.csdn.net/a910626/article/details/46011737

希望大家都把基礎學紮實點,別像我一樣在這種低級錯誤上一直找不到頭緒,哭。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章