3

我有自己的布局

public class MyLayout extends ViewGroup

在那个布局里面我放了一些按钮。这很好用。但我尝试添加 LayoutParams

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

并在 MyLayout 中访问它

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

我只看到 0 作为高度和宽度。我的代码有什么问题?

4

1 回答 1

2

LayoutParams尝试在课堂上创建自己的MyLayout

像这样的东西:

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

然后,您将需要覆盖MyLayout类中的以下方法:

  @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);
  }
于 2012-11-02T13:37:03.063 回答