Get ImageView width and height

与世无争的帅哥 提交于 2019-12-25 07:30:45

问题


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.



来源:https://stackoverflow.com/questions/17479391/get-imageview-width-and-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!