gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:34:09 24 4
gpt4 key购买 nike

我有自己的布局

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com