如何创建要在自定义布局上使用的自定义LayoutParams?
我非常精通基于ViewGroup的复杂自定义布局.我唯一缺少的是能够创建自定义LayoutParams的功能.我真的需要获得利润的能力,为什么不创建其他额外的参数以传递给父代.
I'm fairly proficient at creating complex custom layouts based on ViewGroup. The only thing I'm missing is the ability to create my custom LayoutParams. I really need the ability to get the margins and why not create other extra params to pass in to the parent.
如何创建自定义LayoutParam并通过xml使用它?我尝试使用LinearLayout.LayoutParam,但是由于父级不是LinearLayout,它显然崩溃了.如何在自定义布局上使用LayoutParams?
How can I go about creating a custom LayoutParam and using it via xml? I tried using a LinearLayout.LayoutParam but it's obviously crashing since the parent is not a LinearLayout. How can I work with LayoutParams on custom layouts?
更新:
到目前为止,我一直坚持使用FrameLayout并重写onMeasure和onLayout函数自己进行布局.这确实提供了FrameLayout.LayoutParams.我猜孩子们必须支持自定义LayoutParam?
As of now I'm sticking with using a FrameLayout and overriding the onMeasure and onLayout functions to do the layout myself. This does provide FrameLayout.LayoutParams. I'm guessing the childs would have to support the custom LayoutParam?
在您的自定义布局中,创建扩展ViewGroup.LayoutParams
的嵌套类.然后覆盖一些方法(在我的示例中,所有必需的方法).这是我的一个自定义布局的精简版:
In your custom layout, create a nested class extending ViewGroup.LayoutParams
. Then override some methods (all of the required ones are in my example). Here's a stripped-down version of one of my custom layouts:
public class MyLayout extends ViewGroup {
public MyLayout(Context context) {
}
public MyLayout(Context context, AttributeSet attrs) {
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return generateDefaultLayoutParams(); // TODO Change this?
}
public static class LayoutParams extends ViewGroup.LayoutParams {
public LayoutParams() {
}
public LayoutParams(int width, int height) {
}
public LayoutParams(Context context, AttributeSet attrs) {
}
}
}
进一步的解释:如何创建FlowLayout (感谢您的链接 Luksprog !)
Further explanation: How to create a FlowLayout (thanks for the link Luksprog!)