Android:onViewCreated中Fragment中检索到的视图为null



我正试图在overridenonViewCreated函数中检索片段的视图。以下是我的onCreateViewonViewCreated方法代码:

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.alarms, container, false)
// UI initialization: Set options of the drop-down menu
// Set the contents of the drop-down menu (Spinner)
val spinnerArray =
arrayOf("Followed Parties", "All Events", "Your Alarms", "Events You Haven't Set an Alarm For")
val alarmOptions = root.findViewById<Spinner>(R.id.alarm_viewing_options)
val adapter = ArrayAdapter(
requireContext(),
android.R.layout.simple_spinner_item,
spinnerArray
)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
alarmOptions.adapter = adapter

return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
println("Alarm List: " + activity!!.findViewById(R.id.alarmList) as LinearLayout?)
}

在倒数第二行代码中,我尝试检索其中一个视图(片段布局中的R.id.alarmList)(R.layout.alarms((。但是,当我打印出它的值时,它为null,表示没有找到View。考虑到onViewCreated是在onCreateView之后调用的(其中我对布局R.layout.alarms进行了膨胀(,并且视图R.id.alarmList明显存在于R.layout.alarmsXML(alarms.xml(:中,这似乎很奇怪

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.main.EventsFragment">
<Spinner
android:id="@+id/alarm_viewing_options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="8dp"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:paddingRight="7dp"
android:paddingBottom="7dp"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/alarmList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/pagination_menu" />
</LinearLayout>

您找错了视图的位置,您正试图在Activity作用域中用行找到它

println("Alarm List: " + activity!!.findViewById(R.id.alarmList) as LinearLayout?)

将其更改为

println("Alarm List: " + view!!.findViewById(R.id.alarmList) as LinearLayout?)

这通常是因为您使用activityfindViewById;所以它指向的是活动布局,而不是片段布局。。相反,您可以使用onViewCreated()requireView()view参数

println("Alarm List: " + requireView().findViewById(R.id.alarmList) as LinearLayout?)

最新更新