My question is similar to this question. I’ve used this code to extend ImageView to form TouchImageView. In my onCreate() method, I want to call
setImage(Bitmap bm, int displayWidth, int displayHeight)
but I don’t know the width or height to use. When I call getHeight(), it gives me zero.
I tried to avoid the 0 using kcoppock‘s answer to the previously mentioned question, but was unsuccessful. The onPreDraw() listener is called several times per second and I can’t figure out how to only call it once.
That’s a brittle approach for something like this. Android Views are measured by their parent View using the
onMeasuremethod. By providing an initial size to asetImagemethod to scale to (and especially if you set it based on the display size) you’re inviting complexity whenever you want to nest this View within others. Larger screen devices like tablets are a good example of this.A more idiomatic approach would implement the
setImagemethod of TouchImageView without the width/height parameters at all. Instead it would defer setting the scale and matrices until measurement and implementonMeasuresomething like this:Where the
setInitialScalemethod does everything that the linkedsetImagemethod does after the call tosuper.setImageBitmap.setImageshould also set themNeedsInitialScalefield totrue.This way you will never need to worry about the initial size to use, it will be obtained automatically from the View during normal measurement whenever a new image is set.