2012-08-15 61 views
12

我很擅长创建基于ViewGroup的复杂自定义布局。我唯一缺少的是创建自定义LayoutParams的能力。我真的需要获得边距的能力,为什么不创建其他额外的参数传递给父项。如何创建要在自定义布局上使用的自定义LayoutParams?

我该如何去创建一个自定义LayoutParam并通过xml使用它?我尝试使用LinearLayout.LayoutParam,但它显然崩溃,因为父母不是LinearLayout。我如何在LayoutParams上使用LayoutParams?

更新:

截至目前,我与使用的FrameLayout和重写onMeasure和onLayout功能进行布局自己坚持。这确实提供了FrameLayout.LayoutParams。我猜孩子们将不得不支持自定义的LayoutParam?

+2

请参阅此链接(有关的FlowLayout最后部分):HTTP:/ /www.parleys.com/#st=5&id=2191&sl=38。 – Luksprog 2012-08-15 14:57:17

+0

伟大的链接!完善! – Jona 2012-08-15 18:10:05

+0

上面的链接不起作用。这一个可能会有所帮助:https://github.com/ApmeM/android-flowlayout – 2017-07-24 13:26:02

回答

19

在您的自定义布局中,创建一个扩展ViewGroup.LayoutParams的嵌套类。然后重写一些方法(所有必需的都在我的例子中)。这里是我的自定义布局中的一个精简版本:

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) { 

     } 

    } 

} 

进一步解释:How to create a FlowLayout(!感谢您的链接Luksprog

+0

后@Luksprog已经死了!感谢您发布一些代码,因为其他人会发现它有帮助! – Jona 2012-08-15 18:11:49