为什么getWidth()大于getLayoutParams()。宽度有时?

时间:2013-07-23 13:20:34

标签: android android-layout

我的修复代码ImageView

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();
        }
    });

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

因为getWidth()和getLayoutParams()。width是不同的东西。第一个涉及View,第二个是对父级的布局请求。如果父级无法匹配请求,则View可能以不同的宽度布局。在这种情况下,您已在布局高度中请求了MATCH_PARENT,因为ImageView的默认scaleType为FIT_CENTER,因此保持内容宽高比,以便宽度发生变化。

相关问题