我正在成功地使用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属性?很明显,当导航到相机碎片时。这是某种生命周期问题吗?当导航到摄像机时,它是否被重新初始化?
感谢你的指点。
发布于 2021-05-12 11:45:21
视图在导航到另一个片段时被销毁,因此绑定不再有效。通常情况下,这可以通过在片段retainInstance中将true设置为onViewCreated来解决,但现在已经不再推荐了(尽管我不同意取消推荐,但Google认为应用程序只能简单,所以现在重新加载复杂的布局将是一件昂贵的事情)。您可以使用retainInstance,或者将回调返回的照片对象设置为某个变量,并在调用onCreateView时设置它。
https://stackoverflow.com/questions/67501448
复制相似问题