Although this solution is similar to the ones below, I still put it out to show you that you can still setup the viewTreeObserver in other places like in onStart() because there is a confusion on where to put it. So this is just another way of doing it.
private var imageViewWidth = 0
private var imageViewHeight = 0
private fun updatePhotoView() {
if (photoFile.exists()) {
val bitmap = getScaledBitmap(photoFile.path, imageViewWidth, imageViewHeight)
photoView.setImageBitmap(bitmap)
} else {
photoView.setImageDrawable(null)
}
}
and then declaring it in onStart()
photoView.apply {
viewTreeObserver.addOnGlobalLayoutListener {
imageViewWidth = width
imageViewHeight = height
}
}