我固定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属性:
编辑:
调试后,我很多我确定,有时requestLayout不重新测量图像视图。这是怎么发生的?
编辑:
我找到了解决办法,但还是不知道原因。解决方案如下:
image.post(new Runnable() {
@Override
public void run() {
image.requestLayout();
}
});
任何想法?
''layout_width'可能在'dp'中指定,'getWidth()'返回像素。这将解释1.5倍的差异,特别是如果您使用hdpi设备。 – Geobits
@Geobits我确信layout_width是在dp中指定的,因为具有相同drawable和相同高度的其他视图具有layout_width = 75和getWidth()== 75. – neworld
这就解释了它,因为我确定'getWidth()'在px中:http://developer.android.com/reference/android/view/View.html#getWidth() – Geobits