【问题标题】:setLayoutParams() method doesn't work in onLayout()setLayoutParams() 方法在 onLayout() 中不起作用
【发布时间】:2015-01-14 08:57:43
【问题描述】:

我尝试在扩展的 LinearLayout 中调整组件的大小。 在方法 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);
}

所以我会在 onLayout() 方法中添加一个 Child 并设置 Size,但什么都不会发生。 Child 是从 View 扩展而来的

【问题讨论】:

  • 你想通过改变布局过程中的布局来达到什么目的?
  • 如果布局中有多个子级,或者 parentLayout 会改变大小,我会将 Child 调整为运行时大小。你明白吗?

标签: android android-linearlayout android-view


【解决方案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)
}

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 2020-08-22
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多