创建自定义视图:onMeasure

时间:2014-05-25 16:40:02

标签: android

我是Android编程的新手,我在这个网站上看到了onMeasure的代码:http://www.jayway.com/2012/12/12/creating-custom-android-views-part-4-measuring-and-how-to-force-a-view-to-be-square/

private static final float RATIO = 4f / 3f;

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = getMeasuredWidth();
    int height = getMeasuredHeight();
    int widthWithoutPadding = width - getPaddingLeft() - getPaddingRight();
    int heigthWithoutPadding = height - getPaddingTop() - getPaddingBottom();

    int maxWidth = (int) (heigthWithoutPadding * RATIO);
    int maxHeight = (int) (widthWithoutPadding / RATIO);

    if (widthWithoutPadding  > maxWidth) {
        width = maxWidth + getPaddingLeft() + getPaddingRight();
    } else {
        height = maxHeight + getPaddingTop() + getPaddingBottom();
    }

    setMeasuredDimension(width, height);
}

代码假设采用任何布局并测量布局为4/3的比例。 他们创建了变量maxWidth和maxHeight,它们分别使用了heightWithoutPadding和widthWithoutPadding - 如果不是相反的话?为什么我们将maxWidth与高度变量相关联?

为什么比率与maxWidth相乘但除以maxHeight?如果我们希望视图是原始视图的4/3,那么两者不应该乘以4/3吗?

0 个答案:

没有答案