Android自定义控件中常见的方法

    /**
     * onMeasure方法的作用时测量空间的大小
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //设定默认值,当属性为wrap_comtent时使用,使用match_parent时是精确模式
        int defaultWidthSpecSize = 200;
        int defaultHeightSpecSize = 200;
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
/**
 *      Mode取值:
 *      UNSPECIFIED:未指定模式,View想多大就多大,父容器不做限制,一般用于系统内部的测量。
 *      AT_MOST:最大模式,对应于wrap_comtent属性,只要尺寸不超过父控件允许的最大尺寸就行。
 *      EXACTLY:精确模式,对应于match_parent属性和具体的数值,父容器测量出View所需要的大小,也就是specSize的值。
 */
        if (widthSpecMode == MeasureSpec.EXACTLY) {
            defaultWidthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        }
        if (heightSpecMode == MeasureSpec.EXACTLY) {
            defaultHeightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        }
        setMeasuredDimension(defaultWidthSpecSize, defaultHeightSpecSize);

    }


自定义属性:

attrs.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomView">
        <attr name="myColor" format="color"/>
    </declare-styleable>
</resources>

在自定义View的构造函数中获取

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        mColor = ta.getColor(R.styleable.CustomView_myColor, Color.GREEN);
        //获取完成后及时释放资源
        ta.recycle();
        init();
    }



猜你喜欢

转载自blog.csdn.net/du_zilin/article/details/78973748