在初始化时在onLayout中为CustomView添加边距

时间:2015-06-16 12:47:55

标签: android android-custom-view android-framelayout

我有一个扩展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;
    }

我想在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);
        }
    }

这些保证金永远不会适用。 有人能解释一下这个解决方案吗?

0 个答案:

没有答案