Android 为什么工具栏在片段中为空?
为什么我的工具栏在片段中等于null 清单中的主主题Android 为什么工具栏在片段中为空?,android,android-toolbar,Android,Android Toolbar,为什么我的工具栏在片段中等于null 清单中的主主题 <!-- Base application theme. --> "Theme.MaterialComponents.Light.NoActionBar" class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedIn
<!-- Base application theme. -->
"Theme.MaterialComponents.Light.NoActionBar"
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
}
}
在日志中,我在工具栏上得到空值 显然它是空的,因为您没有分配和初始化它 只需在
视图
赋值后添加
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
但是,我有Kotlin扩展,它直接引用视图
import kotlinx.android.synthetic.main.fragment\u home.*
手动尝试,据我所知,不再推荐和支持synthetic。或者你可以尝试清理/重建,但我猜这不会有帮助
val toolbar: Toolbar = view.findViewById(R.id.toolbar)