Fragment findViewById
为null
!!!
太久没写安卓了,连基础的东西都忘记了,想在一个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
希望大家都把基础学扎实点,别像我一样在这种低级错误上一直找不到头绪,哭。