【问题标题】:Android Vertical Custom ViewGroupAndroid 垂直自定义 ViewGroup
【发布时间】:2015-07-11 18:22:56
【问题描述】:

我有一个简单的问题。我正在扩展 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

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

【问题讨论】:

    标签: android view viewgroup


    【解决方案1】:

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

    【讨论】:

    • 那也行不通。我想垂直增加,所以当前孩子的顶部只是最后一个 currentTop - 那个孩子的高度。
    【解决方案2】:

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

    顺便说一句,您真的不应该在onLayout() 中衡量儿童。这就是onMeasure() 的用途。

    【讨论】:

    • 好吧,一旦我让孩子们真正出现在屏幕上,我就会解决这个怪癖。可悲的是,递增 curTop 什么也没做。孩子们仍然在屏幕上。
    【解决方案3】:

    解决了。感谢那些回答。

    看来问题是我误解了android的坐标系。

    工作代码:(其中 l & 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      相关资源
      最近更新 更多