setLayoutParams()方法在onLayout()中不起作用

时间:2015-01-14 08:57:44

标签: android android-linearlayout android-view

我尝试在扩展的LinearLayout中调整Component的大小。 在方法onLayout()。

public ExtLinearLayout(Context context, AttributeSet attrs, int defStyle) {
  super(context,attrs,0);
  init(attrs);
}

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

  Log.d(TAG,
        "OnLayout1: Left: " + l + "Right: " + r + "Top: " + t + "Bottom: " + b + " children" + this.getChildCount() + " changed" + changed + " getHeight "
              + this.getMeasuredHeight() + " getWidth " + this.getMeasuredWidth());
  Child c = (SeedBar) this.getChildAt(0);
  c.setLayoutParams(new LinearLayout.LayoutParams(20,this.getMeasuredHeight()-23));
  super.onLayout(changed, l, t, r, b);
}

private void init(AttributeSet attrs) {
  this.setOrientation(LinearLayout.VERTICAL);
  this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
  this.configureChild();
  this.invalidate();

}
private void configureChild() {
  Child c = new SeedBar(getContext());
  c.setLayoutParams(new LayoutParams(20, 100));
  this.addView(c, 0);
}

所以我将添加一个Child并在onLayout()方法中设置大小,但什么都不会发生。 Child从View

扩展

1 个答案:

答案 0 :(得分:1)

尽管已经5岁且未得到解答,但该问题仍然是Google在该问题上搜索量最高的结果。对于试图解决自定义组件问题的其他人,您不应在父onLayout()内的子视图上设置LayoutParams,这只是行不通。相反,您想在子视图上调用layout()

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
  super.onLayout(changed, l, t, r, b);
  int margin = 4
  childView.layout(margin, margin, getWidth()-margin, getHeight()-margin)
}