在自定义ViewGroup中使用onLayout正确布局子级 [英] Correctly layout children with onLayout in Custom ViewGroup
问题描述
我正在创建一个自定义ViewGroup.我确实需要一个在另一个之上的2 FrameLayout;停留在底部的那个必须是20dp,而另一个必须覆盖其余的视图.
I am creating a custom ViewGroup. I does need to have 2 FrameLayout one above the other; the one that stays to the bottom must be 20dp, while the other one must cover the rest of the view.
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
可以正确渲染(从top = 0到bottom =(totalHeight-栏高度),并与父级的宽度匹配),而不会渲染栏.
mContentContainer
gets rendered correctly (from top=0 to bottom=(totalHeight - bar height) and match parent for the width), while the bar is not rendered.
推荐答案
View#layout()
方法中的最后一个参数是 View
的底部.对于您的 bar
,您正在传递 0
,但是它应该是自定义 View
的高度,您可以从> t
和 b
值传递到 onLayout()
中.
The last parameter in the View#layout()
method is the bottom of the View
. For your bar
, you're passing 0
, but it should be the height of your custom View
, which you can figure from the t
and b
values passed into onLayout()
.
bar.layout(0, content.getMeasuredHeight(), bar.getMeasuredWidth(), b - t);
这篇关于在自定义ViewGroup中使用onLayout正确布局子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!