3

I have my own layout

public class MyLayout extends ViewGroup

Inside that Layout I put some buttons. That works fine. But I trie to add LayoutParams

ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(80, 80);
Button btn = new Button(getActivity());                 
btn.setLayoutParams(params);    
myLayout.addView(btn);

and access it in MyLayout

View child = getChildAt(i);
ViewGroup.LayoutParams params = child.getLayoutParams();

I only see 0 as height and width. What is wrong in my code?

Macarse
  • 91,829
  • 44
  • 175
  • 230
user1324936
  • 2,187
  • 4
  • 36
  • 49

1 Answers1

2

Try creating your own LayoutParams inside your MyLayout class.

Something like this:

public static class LayoutParams extends ViewGroup.LayoutParams {
    int x;
    int y;

    public LayoutParams(Context context, AttributeSet attrs) {
      super(context, attrs);
    }

    public LayoutParams(int w, int h) {
      super(w, h);
    }
}

Then you will need to override the following methods in the MyLayout class:

  @Override
  protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof LayoutParams;
  }

  @Override
  protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
  }

  @Override
  public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
  }

  @Override
  protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
    return new LayoutParams(p.width, p.height);
  }
Macarse
  • 91,829
  • 44
  • 175
  • 230