是否可以在其中一个Childs的onLayout事件期间为布局添加视图?
即。
FrameLayout包含View,在View.onLayout()中我想将视图添加到父FrameLayout。
这是因为我需要在FrameLayout上绘制的视图需要子视图尺寸(宽度,高度)来将它们分配到FrameLayout上的特定位置。
我已经尝试过这样做,但没有任何事情被吸引。你知道我怎么能达到同样的效果?或者如果我做错了什么。不知道为什么我无法绘制视图,如果我调用invalidate就会发生事件。
感谢。
答案 0 :(得分:3)
是的,这是可能的。我已经解决了类似的问题(使用以下代码将检查点Button放在SeekBar上的FrameLayout中)(来自SeekBar的覆盖方法):
@Override
protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) {
super.onLayout(changed, left, top, right, bottom);
View child = new Button(getContext());
//child measuring
int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, 0, LayoutParams.WRAP_CONTENT); //mWidthMeasureSpec is defined in onMeasure() method below
int childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);//we let child view to be as tall as it wants to be
child.measure(childWidthSpec, childHeightSpec);
//find were to place checkpoint Button in FrameLayout over SeekBar
int childLeft = (getWidth() * checkpointProgress) / getMax() - child.getMeasuredWidth();
LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
param.gravity = Gravity.TOP;
param.setMargins(childLeft, 0, 0, 0);
//specifying 'param' doesn't work and is unnecessary for 1.6-2.1, but it does the work for 2.3
parent.addView(child, firstCheckpointViewIndex + i, param);
//this call does the work for 1.6-2.1, but does not and even is redundant for 2.3
child.layout(childLeft, 0, childLeft + child.getMeasuredWidth(), child.getMeasuredHeight());
}
@Override
protected synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//we save widthMeasureSpec in private field to use it for our child measurment in onLayout()
mWidthMeasureSpec = widthMeasureSpec;
}
还有ViewGroup.addViewInLayout()方法(它受保护,因此只有在覆盖布局的onLayout方法时才可以使用它)javadoc说它的目的正是我们在这里讨论的,但我不明白为什么它比addView()更好。您可以在ListView中找到它的用法。