屏幕对角线的布局视图

时间:2012-04-30 19:09:10

标签: android android-layout

我目前已经实现了一个自定义的ViewGroup类,它试图在屏幕上均匀地和对角地定位项目(带有drawables的按钮)。

不幸的是,如果物品太大,它们往往会重叠,以确保一切都适合屏幕。

我希望有一种更简单的方法来完成现有布局(API8 +),或者如果有一些简单的东西我可以在我的ViewGroup类中更改以使子视图更小以避免重叠。 (例如让每个孩子查看均匀布局所需的确切大小而不重叠)

这是我的onMeasure课程(没有做任何特别的事情。让孩子自己测量)

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

        measureChildren(widthMeasureSpec, heightMeasureSpec);

         int width = MeasureSpec.getSize(widthMeasureSpec);
         int height = MeasureSpec.getSize(heightMeasureSpec);

        setMeasuredDimension(width, height);
    }

编辑:如果我更改onMeasure手动测量儿童到某个宽度/高度,他们会被剪裁。看起来儿童视图(或其可绘制的)实际上并不适合放在测量范围内。

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

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        int newChildWidth = width / getChildCount();
        int newChildHeight = height / getChildCount();

        final int size = getChildCount();
        for (int i = 0; i < size; ++i) {
            View child = getChildAt(i);

            child.measure(MeasureSpec.EXACTLY | newChildWidth, MeasureSpec.EXACTLY | newChildHeight);
        }

        setMeasuredDimension(width, height);
    }

1 个答案:

答案 0 :(得分:1)

到目前为止,您已经有了正确的想法,如果您希望子视图与对角线完全对齐,那么封闭式ViewGroup的工作就是为MeasureSpec提供MeasureSpec.EXACTLY来实现这一目标。 {1}}会告诉每个孩子有多大。您也可以将其换成MeasureSpec.AT_MOST,以允许内容较少的孩子变小,他们将永远不会超过您提供的大小,而EXACTLY每次都会使它们大小相同。

您现在描述的问题是在没有View个自定义的情况下无法真正解决的问题。 Android视图完全独占于“将视图调整为其内容”的范例,而不是“将内容调整为视图大小”。因此,如果您告诉Button小于绘制文本/图像内容所需的空间,它将只是剪辑。此规则的一个例外是ImageView。如果您想绕过这一点,则需要自定义Button以根据onMeasure()

中提供的规范调整文字大小和绘图尺寸

另一种可能的选择,因为无论如何都要自定义ViewGroup,就是使用子静态转换。通过调用setStaticTransformationsEnabled(true)中的ViewGroup并覆盖getChildStaticTransformation(),您可以将比例因子应用于希望大于特定大小的每个子视图。此转换类似于动画的工作方式,因此整个视图将按比例缩小。

HTH