I'm using viewBinding successfully and never encountered this problem before. The property is initialized in onViewCreated like so:
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)
}
I then have a button which opens the camera, like so (also in onViewCreated):
// Button to open camera
viewBinding.takePictureButton.setOnClickListener {
findNavController().navigate(R.id.action_main_fragment_to_camera)
}
My main fragment implements an interface function declared in the camera fragment. This is to know whether the user picked an image or dismissed the camera without picking an image. Like so:
// 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")
}
}
How can my viewBinding property not be initialized here? It obviously is when navigating to camera fragment. Is this a lifecycle issue of some sort? Is it deinitialized when navigating to camera?
Thankful for any pointers.