将LayoutParams传递给ViewGroup不起作用

时间:2012-09-12 21:25:24

标签: android viewgroup

我有自己的布局

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作为高度和宽度。我的代码出了什么问题?

1 个答案:

答案 0 :(得分: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);
  }