1

I have an ImageView which will display an image from the web. I used a AsyncTask to load the image and render the image in the onPostExecute event of the AsnycTask. The image loaded from the web may be very large in size, and cannot be decoded in a phone, so I have to know the size of the image view and re-size the image at run-time.

The View class has getWidth and getHeight methods, but I do not know when it is safe to invoke them. I tried to call these methods in the containing Fragments' onCreateView event, but both return 0; if I call these methods in the onPostExecute event of the AsyncTask, the return value is non-zero and correct.

So I am thinking when is the best point to call these methods and get the view's size.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
David S.
  • 10,578
  • 12
  • 62
  • 104

3 Answers3

0

You should call them in the onPostExecute method of the async task. It is returning 0 in onCreateView as the view is not inflated with the image as yet.

Rajdeep Dua
  • 11,190
  • 2
  • 32
  • 22
  • But I also see cases that the returning size is 0 in the onPostExecute method. That is why I post this question. I want to know when it is safe to retrieve the size value – David S. Dec 27 '11 at 06:37
0

If it is possible then set the android:scaleType="fitXY" attribute in the ImageView.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
0

This is one of the things android does really badly. There is no hook you can access to tell when a view, activity, or fragment has actually been measured. The best thing to do is set a default size for the image view in dp (preferably in xml, but you can also do it programmatically using LayoutParams). Then as Paresh suggested, you can just use scaleType to resize the images.

If you really want to get the width and height of a view, you will need to subclass the view and override onSizeChanged and do whatever it is you want to do based on the width and height there.

Keep in mind that if you are downloading multiple really large images from the web and then resizing them just using image views scaleType you will probably run into memory warnings and exceptions in some phones. You might want to take a look at the following thread: Strange out of memory issue while loading an image to a Bitmap object

Community
  • 1
  • 1
Sam Judd
  • 7,317
  • 1
  • 38
  • 38