在Custom ViewGroup中使用onLayout正确布局子项

时间:2016-08-07 02:11:08

标签: android android-custom-view android-viewgroup

我正在创建一个自定义ViewGroup。我确实需要2个FrameLayout一个在另一个之上;停留在底部的那个必须是20dp,而另一个必须覆盖视图的其余部分。

onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(widthSize, heightSize);

    final View content = getChildAt(CONTENT_INDEX);
    final View bar = getChildAt(BAR_INDEX);

    content.measure(
        MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(heightSize - getPixels(BAR_HEIGHT), MeasureSpec.EXACTLY)
    );

    bar.measure(
        MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(getPixels(BAR_HEIGHT), MeasureSpec.EXACTLY)
    );

onLayout

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    mInLayout = true;

    final View content = getChildAt(CONTENT_INDEX);
    final View bar = getChildAt(BAR_INDEX);

    if (content.getVisibility() != GONE) {
        content.layout(0, 0, content.getMeasuredWidth(), content.getMeasuredHeight());
     }

     if (bar.getVisibility() != GONE) {
         bar.layout(0, content.getMeasuredHeight(), bar.getMeasuredWidth(), 0);
     }

     mInLayout = false;
     mFirstLayout = false;
 }
    }

我要添加到此自定义ViewGroup的视图

LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

mContentContainer = new FrameLayout(getContext());
mContentContainer.setLayoutParams(lp);

mBarContainer = new FrameLayout(getContext());
mBarContainer.setLayoutParams(lp);

// ... adding stuff to both containers ....

addView(mContentContainer, 0);
addView(mBarContainer, 1);

问题

mContentContainer被正确渲染(从顶部= 0到底部=(totalHeight - 条形高度)并匹配宽度的父级),而条形图未渲染。

enter image description here

1 个答案:

答案 0 :(得分:1)

View#layout()方法中的最后一个参数是View的底部。对于bar,您传递的是0,但它应该是自定义View的高度,您可以从tb中找到该高度值传递到onLayout()

bar.layout(0, content.getMeasuredHeight(), bar.getMeasuredWidth(), b - t);