https://kotlinlang.org logo
#android
Title
# android
c

Chethan

07/30/2020, 7:04 AM
Dear Team, I want to find out width and height of the view which is holding wrap content OR match parent . we know that height and width of the view will be available only when the view is shown on the screen, once the view is drawn to screen. Is there way I can find out this earlier before the view is drawn on the screen ? My requirement is to make network call to bring exact image size which is same as view size on the screen
o

OG

07/30/2020, 7:52 AM
If I understand what you're asking correctly, since onMeasure() is called before onDraw(), you do have the ability to figure out the size of a view before it's actually drawn. So just create a custom view or viewgroup (depending on your useCase) and before returning the result in onMeasure(), you can take your measured width/height and pass it to your network layer to fetch the image or image size or w/e and when you get that result you can do whatever it is you need to do in your custom view then trigger onDraw() manually via calls to requestLayout() or invalidate (). ( I don't remember the 4am which one triggers which methods to be called ha). Hope that helps or at least gives you an idea. Again, I may have misunderstood your question but this is my guess given my understanding. Cheers.
a

Adam Powell

07/30/2020, 1:31 PM
I think for this to make a visible difference for users that distinction isn't going to be good enough. Drawing happens synchronously after layout, there isn't time in between to complete a network request and not have an intermediate loading state of some kind on the overwhelming majority of real world networks. Libraries like coil, glide and picasso will do what you described already but network IO still isn't instant.
o

OG

07/30/2020, 3:22 PM
Yeah, I hope my explanation didn't suggest that. But with your own custom view you can set whatever flags you want etc and draw something different based on view state. So when I said to kick off your network request to fetch w/e info it is you need, I'm just saying from onMeasure is when you have the details about size that was needed, and where you can kick off the request on a background thread (using w/e library) and then pass the result back to your custom view (on the main thread) where you can do w/e logic for your new view state then trigger the updates you need
a

Adam Powell

07/30/2020, 3:24 PM
or you can do it without declaring a view subclass with https://developer.android.com/reference/android/view/View.OnLayoutChangeListener
you generally don't want to kick off requests in onMeasure; measurement can happen many times for any one view as a layout tries to find a best fit
o

OG

07/30/2020, 3:25 PM
^ yes this is true as well
Forgot about this at 4am when I was typing ha. Probably some type of listener like the one above is more bug proof and better approach
3 Views