【转载】自定义的listView嵌套在scrollView里时重写onMeasure的原因

转载自:https://blog.csdn.net/xuefu_78/article/details/51760585

在项目开发中,可能经常遇到嵌套ListView、ScrollView的问题,百度一搜,都是现成的代码,而且都是一样的,就是重写onMeasure方法,但是为什么要那么写,这里进行剖析一下下,重点看onMeasure方法,代码如下:

public class ExpandListView extends ListView {

    public ExpandListView(Context context) {
        super(context);
    }

    public ExpandListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExpandListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ExpandListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2
                , MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

要搞明白原理,就要搞懂MeasureSpec这个类,这里我贴一下MeasureSpec类的源码,如下:

public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;
    private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

    /**
     * Measure specification mode: The parent has not imposed any constraint 
     * on the child. It can be whatever size it wants. 
     */
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;

    /**
     * Measure specification mode: The parent has determined an exact size 
     * for the child. The child is going to be given those bounds regardless 
     * of how big it wants to be. 
     */
    public static final int EXACTLY     = 1 << MODE_SHIFT;

    /**
     * Measure specification mode: The child can be as large as it wants up 
     * to the specified size. 
     */
    public static final int AT_MOST     = 2 << MODE_SHIFT;

    /**
     * Creates a measure specification based on the supplied size and mode. 
     *
     * The mode must always be one of the following: 
     * <ul> 
     *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 
     *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 
     *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 
     * </ul> 
     *
     * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 
     * implementation was such that the order of arguments did not matter 
     * and overflow in either value could impact the resulting MeasureSpec. 
     * {@link android.widget.RelativeLayout} was affected by this bug. 
     * Apps targeting API levels greater than 17 will get the fixed, more strict 
     * behavior.</p> 
     *
     * @param size the size of the measure specification 
     * @param mode the mode of the measure specification 
     * @return the measure specification based on size and mode 
     */
    public static int makeMeasureSpec(int size, int mode) {
        if (sUseBrokenMakeMeasureSpec) {
            return size + mode;
        } else {
            return (size & ~MODE_MASK) | (mode & MODE_MASK);
        }
    }

    /**
     * Extracts the mode from the supplied measure specification. 
     *
     * @param measureSpec the measure specification to extract the mode from 
     * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 
     *         {@link android.view.View.MeasureSpec#AT_MOST} or 
     *         {@link android.view.View.MeasureSpec#EXACTLY} 
     */
    public static int getMode(int measureSpec) {
        return (measureSpec & MODE_MASK);
    }

    /**
     * Extracts the size from the supplied measure specification. 
     *
     * @param measureSpec the measure specification to extract the size from 
     * @return the size in pixels defined in the supplied measure specification 
     */
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }

    static int adjust(int measureSpec, int delta) {
        final int mode = getMode(measureSpec);
        if (mode == UNSPECIFIED) {
            // No need to adjust size for UNSPECIFIED mode.  
            return makeMeasureSpec(0, UNSPECIFIED);
        }
        int size = getSize(measureSpec) + delta;
        if (size < 0) {
            Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
                    ") spec: " + toString(measureSpec) + " delta: " + delta);
            size = 0;
        }
        return makeMeasureSpec(size, mode);
    }

    /**
     * Returns a String representation of the specified measure 
     * specification. 
     *
     * @param measureSpec the measure specification to convert to a String 
     * @return a String with the following format: "MeasureSpec: MODE SIZE" 
     */
    public static String toString(int measureSpec) {
        int mode = getMode(measureSpec);
        int size = getSize(measureSpec);

        StringBuilder sb = new StringBuilder("MeasureSpec: ");

        if (mode == UNSPECIFIED)
            sb.append("UNSPECIFIED ");
        else if (mode == EXACTLY)
            sb.append("EXACTLY ");
        else if (mode == AT_MOST)
            sb.append("AT_MOST ");
        else
            sb.append(mode).append(" ");

        sb.append(size);
        return sb.toString();
    }
}

其实里面最重要的是3种模式和3个方法。

首先3种模式

  1. UNSPECIFIED模式,官方意思是:父布局没有给子布局强加任何约束,子布局想要多大就要多大,说白了就是不确定大小(listview就是这个模式)
  2. EXACTLY模式,官方意思是:父布局给子布局限定了准确的大小,子布局的大小就是精确的,父亲给多大就是多大(给定了width,height或者match_parent)
  3. AT_MOST模式,官方意思是:父布局给定了一个最大的值,子布局的大小不能超过这个值,当然可以比这个值小(wrap_content)

怎样重写onMeasure()
示例

//widthMeasureSpec和 heightMeasureSpec的值 由父容器决定

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int width = measureDimension(DEFAULT_WIDTH, widthMeasureSpec);
    int height = measureDimension(DEFAULT_HEIGHT, heightMeasureSpec);

    setMeasuredDimension(width, height);

}

定义一个方法处理 widthMeasureSpec, heightMeasureSpec的值

private int measureHanlder(int measureSpec) {
    int result = defaultSize;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    
    if (specMode == MeasureSpec.EXACTLY) {
        result = specSize;
    } elseif(specMode == MeasureSpec.AT_MOST) {
        result = Math.min(defaultSize, specSize);
    }else{
        result = defaultSize;
    }
    
    returnresult;
}

说明
MeasureSpec.getSize()会解析MeasureSpec值得到父容器width或者height。
MeasureSpec.getMode()会得到三个int类型的值分别为:
MeasureSpec.EXACTLY 、 MeasureSpec.AT_MOST、MeasureSpec.UNSPECIFIED。
MeasureSpec.UNSPECIFIED 未指定,所以可以设置任意大小。
MeasureSpec.AT_MOST MeasureExampleView可以为任意大小,但是有一个上限。比如这种情况:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <mzzo.customview.MeasureView
        android:background="@android:color/holo_blue_dark"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

MeasureSpec.EXACTLY 父容器为MeasureExampleView决定了一个大小,MeasureExampleView大小只能在这个父容器限制的范围之内。
比如这种情况:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="50dp"
    android:layout_height="50dp">

    <mzzo.customview.MeasureExampleView
        android:background="@android:color/holo_blue_dark"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

又或者是这种情况:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <mzzo.customview.MeasureView
        android:background="@android:color/holo_blue_dark"
        android:layout_margin="10dp"
        android:layout_width="50dp"
        android:layout_height="50dp" />
</LinearLayout>

这样当你使用 android:layout_width|android:layout_height属性为:wrap_content时,MeasureView的大小为默认值 100dpx100dp,你也可以根据自己的规则去重写onMeasure()方法。

然后3个方法

  1. public static int makeMeasureSpec(int size, int mode) ,这个方法的作用是根据大小和模式来生成一个int值,这个int值封装了模式和大小信息
  2. public static int getMode(int measureSpec),这个方法的作用是通过一个int值来获取里面的模式信息
  3. public static int getSize(int measureSpec),这个方法的作用是通过一个int值来获取里面的大小信息

在Android里面,一个控件所占的模式和大小是通过一个整数int来表示的,一个int值是怎么来表示模式的大小的呢,这里来看一张图片:

图片

原来,Android里面把int的最高2两位来表示模式,最低30位来表示大小

private static final int MODE_SHIFT = 30;
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;

不确定模式是0左移30位,也就是int类型的最高两位是00
精确模式是1左移30位,也就是int类型的最高两位是01
最大模式是是2左移30位,也就是int类型的最高两位是10

现在在回头看我们之前的代码,如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2
            , MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, expandSpec);
}

我们调用了makeMeasureSpec方法,这个方法是用来生成一个带有模式和大小信息的int值的,第一个参数Integer.MAX_VALUE >> 2,这个参数是传的一个大小值,为什么是这个值呢,我们现在已经知道了,我们要生成的控件,它的大小最大值是int的最低30位的最大值,我们先取Integer.MAX_VALUE来获取int值的最大值,然后左移2位就得到这个临界值最大值了。
当然,我们在手机上的控件的大小不可能那么大,极限值就那么大,实际肯定比那个小,所以这个模式就得选择MeasureSpec.AT_MOST了,最后将生成的这个大小传递给父控件就可以了,super.onMeasure(widthMeasureSpec, expandSpec),这个函数只改变的是控件的高度,宽度没有改变,实际开发当中不管listview有多少条数据,都能一次性展现出来。

小结

  • 重写onMeasure()方法是为了自定义View尺寸的规则
  • 如果你的自定义View的尺寸是根据父控件行为一致,就不需要重写onMeasure()方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271