gpt4 book ai didi

android - 在自定义 ViewGroup 中使用 onLayout 正确布局子项

转载 作者:行者123 更新时间:2023-11-30 01:06:57 25 4
gpt4 key购买 nike

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

测量

@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 的 View

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 得到正确呈现(从 top=0 到 bottom=(totalHeight - bar height) 并匹配父级的宽度),而 bar 没有呈现。

enter image description here

最佳答案

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

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

关于android - 在自定义 ViewGroup 中使用 onLayout 正确布局子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38810279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com