获得ImageView的宽度和高度 [英] Get ImageView width and height

查看:307
本文介绍了获得ImageView的宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想回到我的ImageView的宽度和高度,但要返回0。我打电话ImageView.getWidth()和ImageView.getHeight()中的OnCreate(),我相信ImageView的一直没有有足够的时间进行初始化,因此我得到了错误:

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异常:宽度和高度必须> 0

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

我的问题是:在哪里?是一个好地方,找回我的ImageView的宽度和高度,所以我知道它有足够的时间来进行正确的初始化

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?

注:我试过onWindowFocusChanged(),但得到了同样的问题。

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

干杯!

推荐答案

引自您好Android版(第三版)第81页:

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

由新Android开发常犯的错误是使用它的构造函数中视图的宽度和高度。当视图的构造函数被调用,Android不知道该视图还多大,所以大小设置为零。真正的大小在布局阶段,施工后发生,但被绘制任何东西之前计算。您可以使用onSizeChanged()方法被通知值它们是已知的时候,或者你可以使用的getWidth()和getHeight()甲ODS后,如在的onDraw()方法。

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.

这篇关于获得ImageView的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆