为什么 toolbar = null in fragment?
Why toolbar = null in fragment?
为什么我的工具栏在 fragment 中等于 null?
清单中的主题
<!-- Base application theme. -->
"Theme.MaterialComponents.Light.NoActionBar"
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".home.HomeFragment">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="?attr/colorPrimary" />
</LinearLayout>
HomeFragment.kt
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
(activity as AppCompatActivity).setSupportActionBar(toolbar)
(activity as AppCompatActivity).supportActionBar?.title = "Title"
Log.i("HomeFragment", "$toolbar")
return view
}
}
并且在日志中我在工具栏上得到空值!!
显然它是空的,因为你没有分配和初始化它。
在view
赋值后添加
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
为什么我的工具栏在 fragment 中等于 null?
清单中的主题
<!-- Base application theme. -->
"Theme.MaterialComponents.Light.NoActionBar"
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".home.HomeFragment">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="?attr/colorPrimary" />
</LinearLayout>
HomeFragment.kt
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
(activity as AppCompatActivity).setSupportActionBar(toolbar)
(activity as AppCompatActivity).supportActionBar?.title = "Title"
Log.i("HomeFragment", "$toolbar")
return view
}
}
并且在日志中我在工具栏上得到空值!!
显然它是空的,因为你没有分配和初始化它。
在view
赋值后添加
val toolbar: Toolbar = view.findViewById(R.id.toolbar)