Add margin to a CustomView in onLayout at initialization

568 views Asked by At

I have a custom view which extends FrameLayout:

    public SlidingDrawer(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingDrawer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //get the attributes specified in attrs.xml using the name we included
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.SlidingLayer, 0, 0);

        init = true;
    }

I want to add some margin to layout in the customView:

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        super.onLayout(changed, l, t, r, b);

        if(init) { 
             init = false;

             MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
             final View parent = (View) getParent();
             params.bottomMargin = mOffsetDistance - getHeight();
                    params.topMargin = parent.getHeight()  - mOffsetDistance ;
             setLayoutParams(margins);
        }
    }

These margins will never apply. Can anyone explain me the solution?

0

There are 0 answers