2013-07-23 11 views
0

我固定ImageView代码:为什么getWidth()有时会比getLayoutParams()。width大?

private void fixImageWidth() { 
    int parentHeight = getHeight(); 
    if (parentHeight == 0 || getParent() == null) 
     return; 

    Drawable drawable = image.getDrawable(); 
    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) image.getLayoutParams(); 
    if (drawable != null) { 
     int height = drawable.getIntrinsicHeight(); 
     int width = drawable.getIntrinsicWidth(); 
     lp.width = (int) ((float)(parentHeight - lp.topMargin * 2)/height * width); 
    } else { 
     lp.width = LayoutParams.WRAP_CONTENT; 
    } 

    image.requestLayout(); 
} 

但有时实际图像边界不会改变。下面你可以看到该对象的HierarchyViewer属性:

HierarchyView properties

编辑:

调试后,我很多我确定,有时requestLayout不重新测量图像视图。这是怎么发生的?

编辑:

我找到了解决办法,但还是不知道原因。解决方案如下:

image.post(new Runnable() { 
     @Override 
     public void run() { 
      image.requestLayout(); 
     } 
    }); 

任何想法?

+0

''layout_width'可能在'dp'中指定,'getWidth()'返回像素。这将解释1.5倍的差异,特别是如果您使用hdpi设备。 – Geobits

+0

@Geobits我确信layout_width是在dp中指定的,因为具有相同drawable和相同高度的其他视图具有layout_width = 75和getWidth()== 75. – neworld

+1

这就解释了它,因为我确定'getWidth()'在px中:http://developer.android.com/reference/android/view/View.html#getWidth() – Geobits

回答

2

因为getWidth()和getLayoutParams()。width是不同的东西。第一个涉及视图,第二个是对父级的布局请求。如果父代不能匹配请求,那么View可能以不同的宽度进行布局。在这种情况下,您已经在布局高度中请求了MATCH_PARENT,并且由于ImageView的默认缩放类型为FIT_CENTER,因此内容宽高比将保持不变,宽度将会更改。

+0

我将'adjustViewBounds'设置为false。为什么'requestLayout'不能通过新的'getLayoutParams()。width'设置来重新计算和重新计算宽度? – neworld

+0

我确定了问题。有时候'View.requestLayout'不会重新测量图像。为何会发生这种情况? – neworld

相关问题