kotlin片段错误NullPointerException



我的完整代码

class BlankFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.mainex, container, false)
val groupAdapter = GroupAdapter<ViewHolder>().apply {
spanCount = 2
}
recycler_view.apply {
//error NullPointerException in this line
layoutManager = GridLayoutManager(rootView.context, groupAdapter.spanCount).apply {
spanSizeLookup = groupAdapter.spanSizeLookup
}
adapter = groupAdapter
}

var headerTab: ArrayList<mTop>
headerTab = arguments?.getSerializable("headertab") as ArrayList<mTop>

for (h in 0 until headerTab.size) {
val header = headerTab.get(h).kategori
ExpandableGroup(ExpandableHeaderItem(header), true).apply {
for (c in 0 until headerTab[h].sub.size) {
val gambar = (headerTab[h].sub).get(c).gambar
val nama_menu = (headerTab[h].sub).get(c).nama_menu
add(Section(FancyItem(gambar, nama_menu)))
}
groupAdapter.add(this)
}
}

我正试图在表格布局片段中显示回收视图并且出现错误,可能问题来自rootView.context

layoutManager = GridLayoutManager(rootView.context, groupAdapter.spanCount).apply {
spanSizeLookup = groupAdapter.spanSizeLookup
}

谢谢:((对不起,我的英语不好(

在创建视图之前,您将LayoutManager设置为recyclerView。应该在onViewCreated((方法或xml文件中执行此操作。仅在膨胀视图时使用onCreateView((。然后使用onViewCreated((进行其他需要对视图进行的设置。

完成。这是我使用单独的onCreateView和onViewCreate的完整修复代码。感谢所有

class FragBaru : Fragment() {
private lateinit var rv: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.mainex, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
rv = view.findViewById(R.id.recycler_view)
val groupAdapter = GroupAdapter<ViewHolder>().apply {
spanCount = 2
}
rv.apply {
layoutManager = GridLayoutManager(rootView.context, groupAdapter.spanCount).apply {
spanSizeLookup = groupAdapter.spanSizeLookup
}
adapter = groupAdapter
}
var headerTab: ArrayList<mTop>
headerTab = arguments?.getSerializable("headertab") as ArrayList<mTop>

for (h in 0 until headerTab.size) {
val header = headerTab.get(h).kategori
ExpandableGroup(ExpandableHeaderItem(header), true).apply {
for (c in 0 until headerTab[h].sub.size) {
val gambar = (headerTab[h].sub).get(c).gambar
val nama_menu = (headerTab[h].sub).get(c).nama_menu
add(Section(FancyItem(gambar, nama_menu)))
}
groupAdapter.add(this)
}
}
}

companion object {
fun newInstance(headertab: ArrayList<mTop>): FragBaru {
val f = FragBaru()
val args = Bundle()
args.putSerializable("headertab", headertab)
f.setArguments(args)
return f
}
}

}

相关内容