我正在成功使用 viewBinding 并且以前从未遇到过这个问题。该属性在 onViewCreated 中初始化,如下所示:
private lateinit var viewBinding: FragmentMainBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Create a binding object to the layout
viewBinding = FragmentMainBinding.bind(view)
}
然后我有一个打开相机的按钮,就像这样(也在 onViewCreated 中):
// Button to open camera
viewBinding.takePictureButton.setOnClickListener {
findNavController().navigate(R.id.action_main_fragment_to_camera)
}
我的主要片段实现了在相机片段中声明的接口函数。这是为了知道用户是选择了图像还是在没有选择图像的情况下关闭了相机。像这样:
// Interface declared in CameraFragment
interface ImageCaptureListener {
fun onUserDismissedCamera(userPickedImage: Boolean)
}
// Implementation of interface function in main fragment
override fun onUserDismissedCamera(userPickedImage: Boolean) {
if(userPickedImage) {
println("User picked image")
//** The app crashes when trying to set image in viewBinding.mainFragmentImageView
} else {
println("User did NOT picked image")
}
}
我的 viewBinding 属性怎么不能在这里初始化?显然是在导航到相机片段时。这是某种生命周期问题吗?导航到相机时是否取消初始化?
感谢任何指示。