android - 将 LayoutParams 传递给 ViewGroup 不起作用

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

最佳答案

尝试在您的 MyLayout 类中创建您自己的 LayoutParams

像这样:

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

关于android - 将 LayoutParams 传递给 ViewGroup 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12396408/

相关文章:

java - 如何在 Java (Android) 中使用 getMonth 添加前导零

android - 以编程方式将 View 添加到 Android Viewgroup

android - 自定义 Listview View NullPointerException

android - 通过whatsapp分享图片和文字

android - Firebase 作为 Android 应用后端

android - 如何在 Android 版 map v2 中将版权移至顶部?

android - 搜索栏自定义 : progress and secondaryProgress property not stretch pictures default

android - 以编程方式将 fragment 添加到 View 组

java - 动态添加按钮到 fingerpaint android api 演示

android - 复合控制转发状态