After some research, here is how I set up a tree observer to get the dimensions of the image view when it’s inflated, so we can use the dimension to scale our image.
1- create treeObserver, viewWidth, viewHeight variables in crime fragment:
class CrimeFragment: Fragment(), DatePickerFragment.Callbacks, TimePickerFragment.Callbacks {
..........................
private lateinit var treeObserver: ViewTreeObserver
private var viewWidth = 0
private var viewHeight = 0
2- In onCreateView, initialize the treeObserver and apply the GlobalLayoutListiner method to it:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
.........................
treeObserver = photoView.viewTreeObserver
treeObserver.addOnGlobalLayoutListener {
viewWidth = photoView.width
viewHeight = photoView.height
}
return view
}
3- change updatePhotoView() method to take two arguments, width and height:
private fun updatePhotoView(width: Int, height: Int) {
if (photoFile.exists()) {
val bitmap = getScaledBitmap(photoFile.path, width, height )
photoView.setImageBitmap(bitmap)
}
else {
photoView.setImageDrawable(null)
}
}
Note that, for best practice, the observer should be removed after been used. for more info check:
https://antonioleiva.com/kotlin-ongloballayoutlistener/