自定义布局的Onlayout方法扩展了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来控制位置)


我一直在努力解决这个问题。 它看起来很长时间以来一直被问到,但这是我做了什么来实现它的工作。 也许它会帮助某个人。

扩展LinearLayout意味着如果你希望它像LinearLayout一样显示你的子视图,你不必重写onLayout。 我所需要做的就是按照预期的方式进行布局,即删除我的onLayout方法,让LinearLayout类负责处理这个问题。


layout()方法的第3个和第4个参数分别是“Right position,relative to parent”和“Bottom position,relative to parent”,而不是您认为它们的宽度和高度。

链接地址: http://www.djcxy.com/p/93297.html

上一篇: Onlayout method on custom layout extending LinearLayout

下一篇: AbsListView LayoutParams Set Layout Gravity