自定义布局上的Onlayout方法扩展LinearLayout

时间:2013-07-25 09:02:54

标签: android android-layout layout android-linearlayout

我有一个扩展LinearLayout的自定义视图。此自定义视图包含几个其他视图,其布局应与LinearLayout完全相同,但是,我没有设法将它们正确放置...所有子视图位于彼此之上,隐藏了之前添加的所有子视图。

我的onLayout和onMeasure如下:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    // Do nothing. Do not call the superclass method--that would start a layout pass
    // on this view's children. PieChart lays out its children in onSizeChanged().
    super.onLayout(changed, l, t, r, b);
    Log.e(LOG_TAG, LOG_TAG + ".onLayout: " + l + ", " + t + ", " + r + ", " + b);

    int iChildCount = this.getChildCount();
    for ( int i = 0; i < iChildCount; i++ ) {
        View pChild = this.getChildAt(i);
        pChild.layout(l, t, pChild.getMeasuredWidth(), pChild.getMeasuredHeight());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Try for a width based on our minimum
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: width: " + widthMeasureSpec + " getWidth: " + MeasureSpec.getSize(widthMeasureSpec));
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: height: " + heightMeasureSpec + " getHeight: " + MeasureSpec.getSize(heightMeasureSpec));
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingLeft: " + getPaddingLeft() + " getPaddingRight: " + getPaddingRight());
    Log.d(LOG_TAG, LOG_TAG + ".onMeasure: getPaddingTop: " + getPaddingTop() + " getPaddingBottom: " + getPaddingBottom());

    // http://stackoverflow.com/a/17545273/474330
    int iParentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int iParentHeight = MeasureSpec.getSize(heightMeasureSpec);

    this.setMeasuredDimension(iParentWidth, iParentHeight);

    int iChildCount = this.getChildCount();
    for ( int i = 0; i < iChildCount; i++ ) {
        View pChild = this.getChildAt(i);
        this.measureChild( pChild, 
                MeasureSpec.makeMeasureSpec(iParentWidth, MeasureSpec.EXACTLY), 
                MeasureSpec.makeMeasureSpec(iParentHeight, MeasureSpec.EXACTLY)
        );
    }
}

如何设置自定义视图的x位置,y位置,宽度和高度? 我已将自定义视图的LayoutParam设置为WRAP_CONTENT,但它仍然表现得像FILL_PARENT,占用了父级中可用的所有可用空间。似乎我所有改变位置或大小的努力根本不起作用(我甚至试图设置Padding以试图控制位置)

2 个答案:

答案 0 :(得分:1)

我在这个问题上挣扎了一段时间。看起来很长一段时间以来它被问到了,但这是我为了让它发挥作用所做的。也许它会帮助某人下线。

扩展LinearLayout意味着如果您希望它显示您的子视图与LinearLayout相同,则不必覆盖onLayout。所有我必须做的就是按照预期将其设置为布局,删除我的onLayout方法并让LinearLayout类来处理它。

答案 1 :(得分:0)

layout()方法的第3和第4个参数是&#34;右侧位置,相对于父级&#34;和&#34;底部位置,相对于父级&#34;分别,不是你似乎考虑的宽度和高度。