Get ImageView width and height

2019-09-09 04:52发布

问题:

I'm trying to return the width and height of my ImageView but keep being returned 0. I'm calling ImageView.getWidth() and ImageView.getHeight() in OnCreate() and I believe the ImageView hasn't had enough time to initialize, thus the error I'm getting:

java.lang.IllegalArgumentException: width and height must be > 0

My question is: Where is a good place to retrieve the width and height of my ImageView so I know it has enough time to be initialized properly?

Note: I've tried onWindowFocusChanged() but get the same issue.

Cheers!

回答1:

Quote from "Hello Android (Third Edition)" page 81:

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged( ) method to be notified of the values when they are known, or you can use the getWidth( ) and getHeight( ) meth- ods later, such as in the onDraw( ) method.