Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ImageView return getWidth, getHeight zero

Tags:

android

I am having problem withh the getWidth / getheight function of ImageView. My xml is as follows:

<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>

and my code is as follows:

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

Please help me solve this proble,. Thank you in advance.

like image 315
Thanh Bui Avatar asked Dec 25 '12 09:12

Thanh Bui


2 Answers

Well, I have found the reason. When I set the visibility, the view had not actually been drawn, so I couldn't use getHeight and getWidth function. I found the solution: use ViewTreeObserver

todayBonus.getViewTreeObserver().addOnPreDrawListener(
    new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
        int finalHeight = todayBonus.getMeasuredHeight();
        int finalWidth = todayBonus.getMeasuredWidth();
            // Do your work here
            return true;
    }
    });
like image 55
Thanh Bui Avatar answered Nov 19 '22 08:11

Thanh Bui


May be you are calling getWidth() and getHeight() too early. The UI has not been sized and laid out on the screen yet, and as a result, the methods are correctly returning 0. Review your whole code again. Or paste your complete code here.

like image 23
Rahul Avatar answered Nov 19 '22 08:11

Rahul