自定义LayoutParams

自定义LayoutParams必须要需要重写几个方法

假设我自定义这个类, 很简单,只是继承LinearLayout的Params而已
不包含任何自己的属性

    public static class LayoutParams extends LinearLayout.LayoutParams {

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        public LayoutParams(int width, int height, float weight) {
            super(width, height, weight);
        }

        public LayoutParams(ViewGroup.LayoutParams p) {
            super(p);
        }

        public LayoutParams(MarginLayoutParams source) {
            super(source);
        }
    }

那么需要重写如下方法


    @Override
    public RadioGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new RadioGroup.LayoutParams(getContext(),attrs);
    }

    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof MutilLineRadioGroup.LayoutParams;
    }

其中,checkLayoutParams 这个方法在更新或者设置LayoutParams的时候会调用,如果不重写,可能会导致设置的属性无效,
至于其他几个方法,我的上一偏博文有讲解params


最后欢迎关注我的微信公众号:云端看大地
自定义LayoutParams_第1张图片

你可能感兴趣的:(android自定义view)