【问题标题】:Onlayout method on custom layout extending LinearLayout自定义布局扩展 LinearLayout 的 Onlayout 方法
【发布时间】:2013-07-25 01:56:10
【问题描述】:

我有一个扩展 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,占用了父视图中的所有可用空间。似乎我所有改变位置或大小的努力都没有奏效(我什至尝试 setPadding 来尝试控制位置)

【问题讨论】:

    标签: android android-layout layout android-linearlayout


    【解决方案1】:

    我为同样的问题苦苦挣扎了一段时间。看起来它已经很久没有被问过了,但这是我为了让它工作而做的。也许它会帮助别人。

    扩展 LinearLayout 意味着如果您希望 onLayout 像 LinearLayout 一样显示您的子视图,则不必覆盖它。要按预期进行布局,我所要做的就是删除我的 onLayout 方法并让 LinearLayout 类来处理。

    【讨论】:

      【解决方案2】:

      layout() 方法的第 3 个和第 4 个参数分别是“相对于父级的正确位置”和“相对于父级的底部位置”,而不是您似乎认为的宽度和高度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-10
        • 1970-01-01
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2014-11-13
        • 1970-01-01
        • 2013-08-09
        相关资源
        最近更新 更多