提问人:IamL 提问时间:8/9/2022 更新时间:8/9/2022 访问量:123
使用 Kotlin 在片段中初始化 RecyclerView 时收到 NullPointerException
Receive NullPointerException when initializing RecyclerView in a fragment using Kotlin
问:
我是一个仍在学习 Kotlin 的新手,我正在尝试在片段中实现回收器视图。但是,我收到了 NullPointerException 错误
java.lang.NullPointerException: view.findViewById(R.id.recycler_view) must not be null
我已经检查了回收商视图的 ID
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EventListActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="@layout/event_item"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
我还使用 view.findViewById() 在片段的 onViewCreated() 中初始化了回收器视图
class EventFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var databaseReference: DatabaseReference
private lateinit var eventRecyclerView: RecyclerView
private lateinit var eventArrayList: ArrayList<Event>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
(activity as AppCompatActivity).supportActionBar?.title = "Event"
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_event, container, false)
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
EventFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
eventRecyclerView = view.findViewById(R.id.recycler_view)
eventRecyclerView.layoutManager = LinearLayoutManager(context)
eventRecyclerView.setHasFixedSize(true)
eventArrayList = arrayListOf<Event>()
getEventData()
}
但是,它没有成功,你们能帮我解决这个问题吗?
答:
0赞
ninhnau19
8/9/2022
#1
您使用错误的视图调用 findViewById,有一些方法可以解决您的问题:
将回收程序视图从 activity.xml 移动到 fragment.xml
你可以像这样从 Fragment 调用 Recycler:
activity?.findViewById.....vv
评论