在android中如何获得视图高度或宽度?

时间:2014-10-08 10:40:02

标签: android

我希望在运行时获取图像视图的高度和宽度, 当我使用img1.getWidth()返回零...

我搜索但建议解决方案对我不起作用.. 有人可以帮助我吗?

下面的代码dos对我不起作用,实际上返回的数字不正确

    img1.post(new Runnable()
    {
        public void run()
        {
            int c = img1.getHeight();
            Toast.makeText(getApplicationContext(), c + "", Toast.LENGTH_LONG).show();

        }
    });

2 个答案:

答案 0 :(得分:2)

尝试img1.getLayoutParams()。width和img1.getLayoutParams()。height

如果它不起作用,请尝试以下

img1.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = img1.getMeasuredWidth();
int height = img1.getMeasuredHeight();

答案 1 :(得分:1)

查看API文档,这method应该是您所需要的。您强制视图在运行时进行自我测量,以便您确切知道视图当前的尺寸,在不同尺寸的屏幕上可能是完全不同的尺寸。

然后,您只需致电getMeasuredWidth()getMeasuredHeight()

用于示例:

img1.measure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY);
int width = img1.getMeasuredWidth();
int height = img1.getMeasuredHeight();

快速提醒,每个Android版本都提供measure()方法,但getMeasuredWidth()和getMeasuredHeight()方法仅适用于Android 4.1及更高版本。

希望这有帮助