Android ImageView返回getWidth,getHeight为零

5

我遇到了有关ImageView的getWidth/getheight函数的问题。 我的xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bonus_popup"
    android:visibility="gone"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/todaybonus"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:src="@drawable/startscreen_todaybonus" />
    <ImageView android:id="@+id/ok_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="acceptBonus"
        android:background="#000000"></ImageView>
</RelativeLayout>

我的代码如下:

if (isDisplayBonus){
    set_blur_background();
    bonusPopup.setVisibility(0);
    Log.i(TAG, "Bonus width: " + todayBonus.getWidth());
    Log.i(TAG, "Bonus height: " + todayBonus.getHeight());
}

请帮我解决这个问题,非常感谢。


这里的bonusPopup是什么?请至少粘贴相关部分。 - Yauraw Gadav
嗨Gaurav,bonusPopup是相对布局。 - Thanh Bui
1
从上到下的活动代码? - Yauraw Gadav
2个回答

8

好的,我已经找到了原因。当我设置可见性时,视图实际上还没有被绘制出来,所以我不能使用getHeight和getWidth函数。 我找到了解决方案:使用ViewTreeObserver。

todayBonus.getViewTreeObserver().addOnPreDrawListener(
    new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
        int finalHeight = todayBonus.getMeasuredHeight();
        int finalWidth = todayBonus.getMeasuredWidth();
            // Do your work here
            return true;
    }
    });

1
你把这个放在哪里?放在onCreate方法里面吗? - yrazlik
请告诉我如果你找到了。 - ChuckKelly

4

也许你过早地调用了getWidth()getHeight()方法。因为UI还没有被尺寸化并在屏幕上布局,所以这些方法会正确地返回0。请重新检查你的整个代码。或者将完整的代码粘贴在这里。


我已经把我的代码放在这里了。在让视图出现后,我调用了getWidth函数。 - Thanh Bui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接