J0k3R
J0k3R

Reputation: 303

setLayoutParams() method doesn't work in onLayout()

I tried to resize my Component in my extended LinearLayout. in the Method 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);
}

So I will add a Child and setUp the Size in the onLayout() Method, but nothing will happen. The Child is extended from View

Upvotes: 1

Views: 910

Answers (1)

seanalltogether
seanalltogether

Reputation: 3552

Despite being 5 years old and unanswered, this question is still the top search result on google for this problem. For anyone else trying to figure out this issue for custom components, you should not set LayoutParams on child views inside the parents onLayout(), it just doesn't work. Instead you want to call layout() on the child view

@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)
}

Upvotes: 1

Related Questions