【问题标题】:Android ImageView return getWidth, getHeight zeroAndroid ImageView 返回getWidth,getHeight 为零
【发布时间】:2012-12-11 08:35:24
【问题描述】:

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是什么?至少粘贴相关部分。
  • 嗨 Gaurav,bonusPopup 是相对布局
  • 活动代码?从上到下。

标签: android


【解决方案1】:

嗯,我找到了原因。当我设置可见性时,实际上并没有绘制视图,所以我不能使用 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;
    }
    });

【讨论】:

  • 你把这个放在哪里?在 onCreate 方法里面?
  • 如果你发现了请告诉我
【解决方案2】:

可能你打电话给getWidth()getHeight() 太早了。 UI 尚未在屏幕上调整大小和布局,因此方法正确返回 0。再次检查您的整个代码。或者在此处粘贴您的完整代码。

【讨论】:

  • 我已经把我的代码放在这里了。让视图出现后,我调用了 getWidth 函数。
猜你喜欢
  • 2011-09-02
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多