告诉Android布局有多大“wrap_content”应该是多大

时间:2012-05-23 10:50:54

标签: android layout

我想创建一个自定义View,这样当它以wrap_content作为维度参数之一和match_parent作为另一个时,它将具有恒定的宽高比,填充设置为match_parent的任何维度,但为布局inflater提供“包装”的其他维度。我认为这是可能的,因为,例如,全屏宽度TextView显然能够要求它有两个,三个或任意数量的文本行的空间(取决于宽度),但不会在通货膨胀时间之前必须知道这一点。

理想情况下,我想要做的是覆盖View子类中的布局方法,以便在视图膨胀时,获取布局信息,并为要包装的“内容”提供自己的维度(即我的固定比例矩形)。

我需要创建很多这些自定义视图并将它们放在各种不同类型的布局中 - 有时使用Adapter - 所以我真的希望尽可能地控制它们的通胀。这样做的最佳技巧是什么?

2 个答案:

答案 0 :(得分:1)

您可以随时在onMeasure中检查是否符合宽高比。

不是我知道的完整答案,但它应该引导你到那里;)

答案 1 :(得分:0)

我现在用以下代码解决了这个问题。值得一提的是,我所覆盖的类是具有自定义子项的自定义ViewGroup,全部使用继承的onMeasure。这些孩子是在施工时创建和添加的,我认为这是必要的。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    float width = MeasureSpec.getSize(widthMeasureSpec);
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);

    float height = MeasureSpec.getSize(heightMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

    float nominalHeight = getResources().getInteger(R.integer.nominalheight);
    float nominalWidth = getResources().getInteger(R.integer.nominalwidth);

    float aspectRatio = nominalWidth / nominalHeight;

    if( widthMode == MeasureSpec.UNSPECIFIED ) { //conform width to height
        width = height * aspectRatio;
    }
    else if (heightMode == MeasureSpec.UNSPECIFIED ) { //conform height to width
        height = width / aspectRatio;
    }
    else if( width / height > aspectRatio //too wide
            && ( widthMode == MeasureSpec.AT_MOST )
            ) { 
        width -= (width - height * aspectRatio);
    }
    else if( width / height < aspectRatio //too tall
            && ( heightMode == MeasureSpec.AT_MOST )
            ) { 
        height -= (height - width / aspectRatio);
    }

    int newWidthMeasure = MeasureSpec.makeMeasureSpec((int)width, MeasureSpec.AT_MOST);
    int newHeightMeasure = MeasureSpec.makeMeasureSpec((int)height, MeasureSpec.AT_MOST);
    measureChildren(newWidthMeasure, newHeightMeasure);

    setMeasuredDimension((int)width, (int)height);
}

我用资源中的名义矩形来定义宽高比,但显然还有很多其他方法可以做到这一点。

感谢Josephus Villarey首先指出我onMeasure(...)

相关问题