View的测量p34-p37

一、 View的测量主要使用的类是:MeasureSpec类,测量的过程中是在onMeasure()这个方法里面进行的。

二、 测量的模式分为三种:

1.EXACTLY:这个是精确值模式,空间中的layout_width和layout_height属性为精确的数值或者为match_parent的时候.

2.AT_MOST:这个是最大值模式,空间中的layout_width和layout_height属性为wrap_content的时候.

3.UNSPECIFIED:这个是不指定大小测量模式,View想多大就有多大,通常情况下自定义View才会有用的.

三、 运用:

View类默认的onMeasure()只支持EXACTLY模式,所以如果在自定义空间的时候不重写onMeasure()的话,就只能够使用EXACTLY模式。如果你想要你自定的View支持wrap_content属性,那么就必须重写onMeasure()方法来进行测量,指定wrap_content时的大小。

onMeasure()方法:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

进行查看源码,最后会调用

setMeasuredDimension(int measuredWidth, int measuredHeight)

这一个方法来设置宽高从而完成测量,所以我们完成测量之后需要使用这个方法来设置宽和高。

通过上述分析,我们重写的onMeasure()方法代码如下所示:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureW(widthMeasureSpec),measureH(heightMeasureSpec));
    }

    private int measureW(int widthMeasureSpec){
        int w = 0;

        //测量宽的主要步骤......

        return w;
    }

    private int measureH(int heightMeasureSpec) {
        int h = 0;

        //测量高的主要步骤.....

        return h;
    }

 

我们进行测量的步骤:

第一步:从MeasureSpec对象中提取出具体的测量mode和size,代码如下所示:

第二步:根据不同的mode进行不同方式的测量计算

第三步:通过setMeasuredDimension(int w , int h)方法赋值

下面贴出测量宽的方法:

/**
     * 测量宽
     *
     * @param widthMeasureSpec
     * @return
     */
    private int measureW(int widthMeasureSpec) {
        int w = 0;
        /**
         * 第一步:取出mode和size
         */
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);

        /**
         * 根据不同的mode进行不同方式的测量计算
         */
        if (specMode == MeasureSpec.EXACTLY) {//精确模式
            w = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {//最大值模式
            w = Math.min(200, specSize);
        }else {

        }

        return w;
    }

 

android群英传 P37

 

posted on 2016-06-25 15:36  Z2  阅读(259)  评论(0)    收藏  举报

导航