2

是否可以在其子项之一的 onLayout 事件期间将视图添加到布局?

IE

FrameLayout 包含 View,在 View.onLayout() 中我想将视图添加到父 FrameLayout。

这是因为我需要在 FrameLayout 上绘制的视图需要子视图尺寸(宽度、高度)才能将它们分配到 FrameLayout 上的特定位置。

我已经尝试这样做了,但什么都没有画出来。你知道我怎样才能达到同样的效果吗?或者如果我做错了什么。不知道为什么我无法绘制视图,如果我调用无效,则事件。

谢谢。

4

1 回答 1

3

是的,这是可能的。我已经使用以下代码(来自 SeekBar 的重写方法)解决了类似的问题(将检查点按钮放置在 SeekBar 上的 FrameLayout 中):

@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中找到它的用法。

于 2011-08-11T09:16:13.510 回答