美文网首页
ListView 原理浅析

ListView 原理浅析

作者: SDY_0656 | 来源:发表于2017-09-20 10:07 被阅读0次

    在android应用开发中,listview使用相当广泛,listview主要用来加载大量的相同类型数据,当然listview 也支持加载不同类型的数据,那么为什么listview能够加载大量数据而不产生OOM呢,现在就从listview的源码说起。
    在listview的源码中有一个内部类RecycleBin,这个类是listview缓存的关键,在里面有一个View[] activeViews 的数组和一个currentScrapViews的SparseArray<View>,还有一个SparseArray<View>[] scrapViews,activeViews指的是在当前屏幕中的view,当viewType只有一个的时候,销毁或者是说移除屏幕外的view就保存在currentScrapViews中,view的类型有多个的时候,就分别保存在scrapViews中。
    首先分析listview加载第一屏的时候,android的view中,view的onMeasure或者onLayout会走至少两趟,如果在listview中走两趟的话,那么数据就会重复,所有listview的绘制有特殊的处理。
    当第一次onLayout的时候,走到最后是走的这个方法:

    /** 
     * Fills the list from pos down to the end of the list view. 
     * 
     * @param pos The first position to put in the list 
     * 
     * @param nextTop The location where the top of the item associated with pos 
     *        should be drawn 
     * 
     * @return The view that is currently selected, if it happens to be in the 
     *         range that we draw. 
     */  
    private View fillDown(int pos, int nextTop) {  
        View selectedView = null;  
        int end = (getBottom() - getTop()) - mListPadding.bottom;  
        while (nextTop < end && pos < mItemCount) {  
            // is this the selected item?  
            boolean selected = pos == mSelectedPosition;  
            View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);  
            nextTop = child.getBottom() + mDividerHeight;  
            if (selected) {  
                selectedView = child;  
            }  
            pos++;  
        }  
        return selectedView;  
    }  
    

    可以看到,这里使用了一个while循环来执行重复逻辑,一开始nextTop的值是第一个子元素顶部距离整个ListView顶部的像素值,pos则是刚刚传入的mFirstPosition的值,而end是ListView底部减去顶部所得的像素值,mItemCount则是Adapter中的元素数量。因此一开始的情况下nextTop必定是小于end值的,并且pos也是小于mItemCount值的。那么每执行一次while循环,pos的值都会加1,并且nextTop也会增加,当nextTop大于等于end时,也就是子元素已经超出当前屏幕了,或者pos大于等于mItemCount时,也就是所有Adapter中的元素都被遍历结束了,就会跳出while循环。

    /** 
     * Obtain the view and add it to our list of children. The view can be made 
     * fresh, converted from an unused view, or used as is if it was in the 
     * recycle bin. 
     * 
     * @param position Logical position in the list 
     * @param y Top or bottom edge of the view to add 
     * @param flow If flow is true, align top edge to y. If false, align bottom 
     *        edge to y. 
     * @param childrenLeft Left edge where children should be positioned 
     * @param selected Is this position selected? 
     * @return View that was added 
     */  
    private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,  
            boolean selected) {  
        View child;  
        if (!mDataChanged) {  
            // Try to use an exsiting view for this position  
            child = mRecycler.getActiveView(position);  
            if (child != null) {  
                // Found it -- we're using an existing child  
                // This just needs to be positioned  
                setupChild(child, position, y, flow, childrenLeft, selected, true);  
                return child;  
            }  
        }  
        // Make a new view for this position, or convert an unused view if possible  
        child = obtainView(position, mIsScrap);  
        // This needs to be positioned and measured  
        setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);  
        return child;  
    }  
    

    这里在首先尝试从RecycleBin当中快速获取一个active view,不过很遗憾的是目前RecycleBin当中还没有缓存任何的View,所以这里得到的值肯定是null。那么取得了null之后就会继续向下运行,然后会调用obtainView()方法来再次尝试获取一个View,这次的obtainView()方法是可以保证一定返回一个View的,于是下面立刻将获取到的View传入到了setupChild()方法当中。那么obtainView()内部到底是怎么工作的呢?我们先进入到这个方法里面看一下:

    /** 
     * Get a view and have it show the data associated with the specified 
     * position. This is called when we have already discovered that the view is 
     * not available for reuse in the recycle bin. The only choices left are 
     * converting an old view or making a new one. 
     *  
     * @param position 
     *            The position to display 
     * @param isScrap 
     *            Array of at least 1 boolean, the first entry will become true 
     *            if the returned view was taken from the scrap heap, false if 
     *            otherwise. 
     *  
     * @return A view displaying the data associated with the specified position 
     */  
    View obtainView(int position, boolean[] isScrap) {  
        isScrap[0] = false;  
        View scrapView;  
        scrapView = mRecycler.getScrapView(position);  
        View child;  
        if (scrapView != null) {  
            child = mAdapter.getView(position, scrapView, this);  
            if (child != scrapView) {  
                mRecycler.addScrapView(scrapView);  
                if (mCacheColorHint != 0) {  
                    child.setDrawingCacheBackgroundColor(mCacheColorHint);  
                }  
            } else {  
                isScrap[0] = true;  
                dispatchFinishTemporaryDetach(child);  
            }  
        } else {  
            child = mAdapter.getView(position, null, this);  
            if (mCacheColorHint != 0) {  
                child.setDrawingCacheBackgroundColor(mCacheColorHint);  
            }  
        }  
        return child;  
    }  
    

    obtainView()方法中的代码并不多,但却包含了非常非常重要的逻辑,不夸张的说,整个ListView中最重要的内容可能就在这个方法里了。那么我们还是按照执行流程来看,首先调用了RecycleBin的getScrapView()方法来尝试获取一个废弃缓存中的View,同样的道理,这里肯定是获取不到的,getScrapView()方法会返回一个null。这时该怎么办呢?没有关系,接着往后执行,调用mAdapter的getView()方法来去获取一个View。那么mAdapter是什么呢?当然就是当前ListView关联的适配器了。而getView()方法又是什么呢?还用说吗,这个就是我们平时使用ListView时最最经常重写的一个方法了,这里getView()方法中传入了三个参数,分别是position,null和this。这个getView就是我们常用的adapter的getView,第一次加载的时候contentview传入的是null,getView()方法接受的三个参数,第一个参数position代表当前子元素的的位置,我们可以通过具体的位置来获取与其相关的数据。第二个参数convertView,刚才传入的是null,说明没有convertView可以利用,因此我们会调用LayoutInflater的inflate()方法来去加载一个布局。接下来会对这个view进行一些属性和值的设定,最后将view返回。那么这个View也会作为obtainView()的结果进行返回,并最终传入到setupChild()方法当中。其实也就是说,第一次layout过程当中,所有的子View都是调用LayoutInflater的inflate()方法加载出来的,这样就会相对比较耗时,但是不用担心,后面就不会再有这种情况了。
    setupChild()方法当中的代码虽然比较多,但是我们只看核心代码的话就非常简单了,刚才调用obtainView()方法获取到的子元素View,然后调用addViewInLayout()方法将它添加到了ListView当中。那么根据fillDown()方法中的while循环,会让子元素View将整个ListView控件填满然后就跳出,也就是说即使我们的Adapter中有一千条数据,ListView也只会加载第一屏的数据,剩下的数据反正目前在屏幕上也看不到,所以不会去做多余的加载工作,这样就可以保证ListView中的内容能够迅速展示到屏幕上。
    然后看看第二次layout的情况,同样首先调用getChildCount()方法来获取子View的数量,只不过现在得到的值不会再是0了,而是ListView中一屏可以显示的子View数量,因为我们刚刚在第一次Layout过程当中向ListView添加了这么多的子View。下面在第90行调用了RecycleBin的fillActiveViews()方法,这次效果可就不一样了,因为目前ListView中已经有子View了,这样所有的子View都会被缓存到RecycleBin的mActiveViews数组当中,后面将会用到它们。

    接下来将会是非常非常重要的一个操作,detachAllViewsFromParent()方法。这个方法会将所有ListView当中的子View全部清除掉,从而保证第二次Layout过程不会产生一份重复的数据。那有的朋友可能会问了,这样把已经加载好的View又清除掉,待会还要再重新加载一遍,这不是严重影响效率吗?不用担心,还记得我们刚刚调用了RecycleBin的fillActiveViews()方法来缓存子View吗,待会儿将会直接使用这些缓存好的View来进行加载,而并不会重新执行一遍inflate过程,因此效率方面并不会有什么明显的影响。
    第二次会进入到fillSpecific()方法,fillSpecific()这算是一个新方法了,不过其实它和fillUp()、fillDown()方法功能也是差不多的,主要的区别在于,fillSpecific()方法会优先将指定位置的子View先加载到屏幕上,然后再加载该子View往上以及往下的其它子View。那么由于这里我们传入的position就是第一个子View的位置,于是fillSpecific()方法的作用就基本上和fillDown()方法是差不多的了,这里我们就不去关注太多它的细节,而是将精力放在makeAndAddView()方法上面。再次回到makeAndAddView()方法。
    最后看一下setupChild这个方法:

    /** 
     * Add a view as a child and make sure it is measured (if necessary) and 
     * positioned properly. 
     * 
     * @param child The view to add 
     * @param position The position of this child 
     * @param y The y position relative to which this view will be positioned 
     * @param flowDown If true, align top edge to y. If false, align bottom 
     *        edge to y. 
     * @param childrenLeft Left edge where children should be positioned 
     * @param selected Is this position selected? 
     * @param recycled Has this view been pulled from the recycle bin? If so it 
     *        does not need to be remeasured. 
     */  
    private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,  
            boolean selected, boolean recycled) {  
        final boolean isSelected = selected && shouldShowSelector();  
        final boolean updateChildSelected = isSelected != child.isSelected();  
        final int mode = mTouchMode;  
        final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&  
                mMotionPosition == position;  
        final boolean updateChildPressed = isPressed != child.isPressed();  
        final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();  
        // Respect layout params that are already in the view. Otherwise make some up...  
        // noinspection unchecked  
        AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();  
        if (p == null) {  
            p = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,  
                    ViewGroup.LayoutParams.WRAP_CONTENT, 0);  
        }  
        p.viewType = mAdapter.getItemViewType(position);  
        if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&  
                p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {  
            attachViewToParent(child, flowDown ? -1 : 0, p);  
        } else {  
            p.forceAdd = false;  
            if (p.viewType == AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {  
                p.recycledHeaderFooter = true;  
            }  
            addViewInLayout(child, flowDown ? -1 : 0, p, true);  
        }  
        if (updateChildSelected) {  
            child.setSelected(isSelected);  
        }  
        if (updateChildPressed) {  
            child.setPressed(isPressed);  
        }  
        if (needToMeasure) {  
            int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,  
                    mListPadding.left + mListPadding.right, p.width);  
            int lpHeight = p.height;  
            int childHeightSpec;  
            if (lpHeight > 0) {  
                childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);  
            } else {  
                childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);  
            }  
            child.measure(childWidthSpec, childHeightSpec);  
        } else {  
            cleanupLayoutState(child);  
        }  
        final int w = child.getMeasuredWidth();  
        final int h = child.getMeasuredHeight();  
        final int childTop = flowDown ? y : y - h;  
        if (needToMeasure) {  
            final int childRight = childrenLeft + w;  
            final int childBottom = childTop + h;  
            child.layout(childrenLeft, childTop, childRight, childBottom);  
        } else {  
            child.offsetLeftAndRight(childrenLeft - child.getLeft());  
            child.offsetTopAndBottom(childTop - child.getTop());  
        }  
        if (mCachingStarted && !child.isDrawingCacheEnabled()) {  
            child.setDrawingCacheEnabled(true);  
        }  
    }  
    

    可以看到,setupChild()方法的最后一个参数是recycled,然后会对这个变量进行判断,由于recycled现在是true,所以会执行attachViewToParent()方法,而第一次Layout过程则是执行的else语句中的addViewInLayout()方法。这两个方法最大的区别在于,如果我们需要向ViewGroup中添加一个新的子View,应该调用addViewInLayout()方法,而如果是想要将一个之前detach的View重新attach到ViewGroup上,就应该调用attachViewToParent()方法。那么由于前面在layoutChildren()方法当中调用了detachAllViewsFromParent()方法,这样ListView中所有的子View都是处于detach状态的,所以这里attachViewToParent()方法是正确的选择。
    经历了这样一个detach又attach的过程,ListView中所有的子View又都可以正常显示出来了,那么第二次Layout过程结束。
    如果ListView中最后一个View的底部已经移入了屏幕,或者ListView中第一个View的顶部移入了屏幕,就会调用fillGap()方法,那么因此我们就可以猜出fillGap()方法是用来加载屏幕外数据的,进入到这个方法中瞧一瞧,如下所示:

    void fillGap(boolean down) {  
        final int count = getChildCount();  
        if (down) {  
            final int startOffset = count > 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :  
                    getListPaddingTop();  
            fillDown(mFirstPosition + count, startOffset);  
            correctTooHigh(getChildCount());  
        } else {  
            final int startOffset = count > 0 ? getChildAt(0).getTop() - mDividerHeight :  
                    getHeight() - getListPaddingBottom();  
            fillUp(mFirstPosition - 1, startOffset);  
            correctTooLow(getChildCount());  
        }  
    }  
    

    down参数用于表示ListView是向下滑动还是向上滑动的,可以看到,如果是向下滑动的话就会调用fillDown()方法,而如果是向上滑动的话就会调用fillUp()方法。那么这两个方法我们都已经非常熟悉了,内部都是通过一个循环来去对ListView进行填充,所以这两个方法我们就不看了,但是填充ListView会通过调用makeAndAddView()方法来完成,又是makeAndAddView()方法,但这次的逻辑再次不同了,所以我们还是回到这个方法瞧一瞧:

    /** 
     * Obtain the view and add it to our list of children. The view can be made 
     * fresh, converted from an unused view, or used as is if it was in the 
     * recycle bin. 
     * 
     * @param position Logical position in the list 
     * @param y Top or bottom edge of the view to add 
     * @param flow If flow is true, align top edge to y. If false, align bottom 
     *        edge to y. 
     * @param childrenLeft Left edge where children should be positioned 
     * @param selected Is this position selected? 
     * @return View that was added 
     */  
    private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,  
            boolean selected) {  
        View child;  
        if (!mDataChanged) {  
            // Try to use an exsiting view for this position  
            child = mRecycler.getActiveView(position);  
            if (child != null) {  
                // Found it -- we're using an existing child  
                // This just needs to be positioned  
                setupChild(child, position, y, flow, childrenLeft, selected, true);  
                return child;  
            }  
        }  
        // Make a new view for this position, or convert an unused view if possible  
        child = obtainView(position, mIsScrap);  
        // This needs to be positioned and measured  
        setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);  
        return child;  
    }  
    

    不管怎么说,这里首先仍然是会尝试调用RecycleBin的getActiveView()方法来获取子布局,只不过肯定是获取不到的了,因为在第二次Layout过程中我们已经从mActiveViews中获取过了数据,而根据RecycleBin的机制,mActiveViews是不能够重复利用的,因此这里返回的值肯定是null。
    既然getActiveView()方法返回的值是null,那么就还是会走到obtainView()方法当中,代码如下所示:

    /** 
     * Get a view and have it show the data associated with the specified 
     * position. This is called when we have already discovered that the view is 
     * not available for reuse in the recycle bin. The only choices left are 
     * converting an old view or making a new one. 
     *  
     * @param position 
     *            The position to display 
     * @param isScrap 
     *            Array of at least 1 boolean, the first entry will become true 
     *            if the returned view was taken from the scrap heap, false if 
     *            otherwise. 
     *  
     * @return A view displaying the data associated with the specified position 
     */  
    View obtainView(int position, boolean[] isScrap) {  
        isScrap[0] = false;  
        View scrapView;  
        scrapView = mRecycler.getScrapView(position);  
        View child;  
        if (scrapView != null) {  
            child = mAdapter.getView(position, scrapView, this);  
            if (child != scrapView) {  
                mRecycler.addScrapView(scrapView);  
                if (mCacheColorHint != 0) {  
                    child.setDrawingCacheBackgroundColor(mCacheColorHint);  
                }  
            } else {  
                isScrap[0] = true;  
                dispatchFinishTemporaryDetach(child);  
            }  
        } else {  
            child = mAdapter.getView(position, null, this);  
            if (mCacheColorHint != 0) {  
                child.setDrawingCacheBackgroundColor(mCacheColorHint);  
            }  
        }  
        return child;  
    }  
    

    这里在第19行会调用RecyleBin的getScrapView()方法来尝试从废弃缓存中获取一个View,那么废弃缓存有没有View呢?当然有,因为刚才在trackMotionScroll()方法中我们就已经看到了,一旦有任何子View被移出了屏幕,就会将它加入到废弃缓存中,而从obtainView()方法中的逻辑来看,一旦有新的数据需要显示到屏幕上,就会尝试从废弃缓存中获取View。所以它们之间就形成了一个生产者和消费者的模式,那么ListView神奇的地方也就在这里体现出来了,不管你有任意多条数据需要显示,ListView中的子View其实来来回回就那么几个,移出屏幕的子View会很快被移入屏幕的数据重新利用起来,因而不管我们加载多少数据都不会出现OOM的情况,甚至内存都不会有所增加。
    写这篇文章主要是帮自己加深理解,原文请参考:
    http://blog.csdn.net/guolin_blog/article/details/44996879

    相关文章

      网友评论

          本文标题:ListView 原理浅析

          本文链接:https://www.haomeiwen.com/subject/dohgsxtx.html