在Activity中创建一个RecyclerView可以正常创建以及显示,然后换了在 Fragment 中一直报错说不能为空。
然后上网查了一下:
结论得出,我们通常把initView
方法写在onCreateView
方法中,但是这个时候view可能并没有返回,所以就找不到了,所以我们可以把初始化操作放在onActivityCreated
或onViewCreated
中
只要把 RecyclerView放到 onViewCreated 中初始化即可:
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //模拟数据 var user1 = UserData() user1.age = "23" user1.sex = "男" user1.userName = "张三" var user2 = UserData() user2.age = "30" user2.sex = "女" user2.userName = "李四" var user3 = UserData() user3.age = "25" user3.sex = "保密" user3.userName = "刘柳" arrayList.add(user1) arrayList.add(user2) arrayList.add(user3) val takePhotoAdapter = TakePhotoAdapter(arrayList) recycler_View.adapter = takePhotoAdapter val gridlayout = GridLayoutManager(context!!, 2) recycler_View.layoutManager=gridlayout }