#Android源码#View的onMeasure方法

来源:互联网 发布:屹然不动而远乎 编辑:程序博客网 时间:2024/06/05 09:06

分析所得

  1. 功能:测量View和它的内容,来决定测量宽度和测量高度。

  2. 该方法由measure(int widthMeasureSpec, int heightMeasureSpec)(两个参数分别是parent告知的宽度和高度参数)调用,并且必须要经过子类重写来提供精确和有效的内容测量。

  3. 约定:当重写该方法时,必须调用setMeasuredDimension(int, int)来保存测量的宽度和高度,否则会引发IllegalStateException异常

  4. 子类有义务保证测量的宽度和高度至少要是view的最小高度和宽度。

  5. 宽高的mode和size封装到MeasureSpec中,详见 #Android源码#MeasureSpec

  6. 宽高是由parent决定的,所以child只能在parent给予的MeasureSpec下来进行宽高的设置

源码如下

    /**     * <p>     * Measure the view and its content to determine the measured width and the     * measured height. This method is invoked by {@link #measure(int, int)} and     * should be overridden by subclasses to provide accurate and efficient     * measurement of their contents.     * </p>     *     * <p>     * <strong>CONTRACT:</strong> When overriding this method, you     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the     * measured width and height of this view. Failure to do so will trigger an     * <code>IllegalStateException</code>, thrown by     * {@link #measure(int, int)}. Calling the superclass'     * {@link #onMeasure(int, int)} is a valid use.     * </p>     *     * <p>     * The base class implementation of measure defaults to the background size,     * unless a larger size is allowed by the MeasureSpec. Subclasses should     * override {@link #onMeasure(int, int)} to provide better measurements of     * their content.     * </p>     *     * <p>     * If this method is overridden, it is the subclass's responsibility to make     * sure the measured height and width are at least the view's minimum height     * and width ({@link #getSuggestedMinimumHeight()} and     * {@link #getSuggestedMinimumWidth()}).     * </p>     *     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.     *                         The requirements are encoded with     *                         {@link android.view.View.MeasureSpec}.     * @param heightMeasureSpec vertical space requirements as imposed by the parent.     *                         The requirements are encoded with     *                         {@link android.view.View.MeasureSpec}.     *     * @see #getMeasuredWidth()     * @see #getMeasuredHeight()     * @see #setMeasuredDimension(int, int)     * @see #getSuggestedMinimumHeight()     * @see #getSuggestedMinimumWidth()     * @see android.view.View.MeasureSpec#getMode(int)     * @see android.view.View.MeasureSpec#getSize(int)     */    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));    }
1 0
原创粉丝点击