Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom LayoutParams to be used on a custom layout?

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.

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?

Update:

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?

like image 313
Jona Avatar asked Aug 15 '12 13:08

Jona


1 Answers

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

        }

    }

}

Further explanation: How to create a FlowLayout (thanks for the link Luksprog!)

like image 119
Joel Sjögren Avatar answered Oct 20 '22 05:10

Joel Sjögren