Android Vertical Custom ViewGroup

时间:2015-07-11 18:22:57

标签: android view viewgroup

我有一个简单的问题。我正在扩展ViewGroup,我想从上到下将按钮对齐到屏幕的右侧。问题是,我的屏幕上没有显示任何内容。我已经确认它不是其他任何问题,只有我的onLayout()覆盖方法。你能救我一下吗?

有问题的代码:

    final int count = getChildCount();
    int curWidth, curHeight, curLeft, curTop;

    //get the available size of child view
    int childLeft = this.getPaddingLeft();
    int childTop = this.getPaddingTop();
    int childRight = this.getMeasuredWidth() - this.getPaddingRight();
    int childBottom = this.getMeasuredHeight() - this.getPaddingBottom();
    int childWidth = childRight - childLeft;
    int childHeight = childBottom - childTop;

    curTop = childTop;
    for (int i = 0; i < count; i++) {
        View child = getChildAt(i);

        //Get the maximum size of the child
        child.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST),
                MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
        curWidth = child.getMeasuredWidth();
        curHeight = child.getMeasuredHeight();

        child.layout(getMeasuredWidth() - getPaddingRight() - curWidth,
                curTop, getMeasuredWidth() - getPaddingRight(), curTop - curHeight);
        curTop -= childHeight;
    }

我在我的代码中添加了一些LOG语句,而且我所拥有的是坦率的真气。

07-11 14:46:46.321  32172-32172/milespeele.canvas D/Miles﹕ LEFT: 912
07-11 14:46:46.322  32172-32172/milespeele.canvas D/Miles﹕ TOP: 1008
07-11 14:46:46.322  32172-32172/milespeele.canvas D/Miles﹕ RIGHT: 1080
07-11 14:46:46.322  32172-32172/milespeele.canvas D/Miles﹕ BOTTOM: 1008

考虑到手机屏幕的尺寸,这些都是有效坐标(对于一个按钮),但没有按钮出现。

3 个答案:

答案 0 :(得分:1)

我没有完全扫描,但我发现curTop - curHeight中有child.layout()作为最后一个参数。它应该是curTop + curHeight吗?

答案 1 :(得分:1)

您正在递减curTop。坐标值会在屏幕下方增加,因此您实际上将子画面布置在ViewGroup顶部的屏幕之外。我想你希望curTop + curHeight作为child.layout()的最后一个参数,我认为最后一行应该是curTop += curHeight

顺便说一句,你真的不应该在onLayout()中测量孩子。这是onMeasure()的用途。

答案 2 :(得分:0)

解决。感谢那些回答。

似乎问题是我误解了android的坐标系。

工作代码:(其中l&amp; r是onLayout()的参数)

    final int count = getChildCount();

    int left = (int) (l + getMeasuredWidth() - buttonMargin - buttonWidth);
    int right = (int) (r - buttonMargin);

    int currentTop = (int) (t + buttonMargin);
    for (int i = 0; i < count; i++) {
        View child = getChildAt(i);
        child.layout(left, currentTop, right, currentTop + buttonHeight);
        currentTop += buttonHeight + buttonMargin;
    }