RecyclerView(三)

Android知识总结

一、预加载流程

RecyclerView.onTouchEventACTION_MOVE事件进入分析

GapWorker mGapWorker;

public boolean onTouchEvent(MotionEvent e) {
    case MotionEvent.ACTION_MOVE: {
        if (mGapWorker != null && (dx != 0 || dy != 0)) {
            //开始进入预加载过程
            mGapWorker.postFromTraversal(this, dx, dy);
        }
    }
}

调用GapWorkerpostFromTraversal方法。GapWorker只要做间隙工作(即View 刷新间隙),对RecyclerView的item做预加载处理

final class GapWorker implements Runnable {
    //GapWorker 的静态实例
    static final ThreadLocal<GapWorker> sGapWorker = new ThreadLocal<>();
    //RecyclerView的缓存
    ArrayList<RecyclerView> mRecyclerViews = new ArrayList<>();

    void postFromTraversal(RecyclerView recyclerView, int prefetchDx, int prefetchDy) {
        if (recyclerView.isAttachedToWindow()) {
            if (RecyclerView.DEBUG && !mRecyclerViews.contains(recyclerView)) {
                throw new IllegalStateException("attempting to post unregistered view!");
            }
            if (mPostTimeNs == 0) {
                mPostTimeNs = recyclerView.getNanoTime();
                //会调用View的Post方法,通过Handler处理任务,活到Runable中
                recyclerView.post(this);
            }
        }

        recyclerView.mPrefetchRegistry.setPrefetchVector(prefetchDx, prefetchDy);
    }
}

View.Post()方法

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        getRunQueue().post(action);
        return true;
    }

执行GapWorker的任务run中执行

    public void run() {
        try {
            TraceCompat.beginSection(RecyclerView.TRACE_PREFETCH_TAG);
            if (mRecyclerViews.isEmpty()) {
                // abort - no work to do
                return;
            }
            final int size = mRecyclerViews.size();
            long latestFrameVsyncMs = 0;
            for (int i = 0; i < size; i++) {
                RecyclerView view = mRecyclerViews.get(i);
                if (view.getWindowVisibility() == View.VISIBLE) {
                    latestFrameVsyncMs = Math.max(view.getDrawingTime(), latestFrameVsyncMs);
                }
            }

            if (latestFrameVsyncMs == 0) {
                // abort - either no views visible, or couldn't get last vsync for estimating next
                return;
            }
            long nextFrameNs = TimeUnit.MILLISECONDS.toNanos(latestFrameVsyncMs) + mFrameIntervalNs;
            prefetch(nextFrameNs);
        } finally {
            mPostTimeNs = 0;
            TraceCompat.endSection();
        }
    }

GapWorker.prefetch方法

    void prefetch(long deadlineNs) {
        buildTaskList();
        flushTasksWithDeadline(deadlineNs);
    }

    private void flushTasksWithDeadline(long deadlineNs) {
        for (int i = 0; i < mTasks.size(); i++) {
            final Task task = mTasks.get(i);
            if (task.view == null) {
                break; // done with populated tasks
            }
            flushTaskWithDeadline(task, deadlineNs);
            task.clear();
        }
    }

    private void flushTaskWithDeadline(Task task, long deadlineNs) {
        long taskDeadlineNs = task.immediate ? RecyclerView.FOREVER_NS : deadlineNs;
        RecyclerView.ViewHolder holder = prefetchPositionWithDeadline(task.view,
                task.position, taskDeadlineNs);
        if (holder != null
                && holder.mNestedRecyclerView != null
                && holder.isBound()
                && !holder.isInvalid()) {
            prefetchInnerRecyclerViewWithDeadline(holder.mNestedRecyclerView.get(), deadlineNs);
        }
    }

    private void prefetchInnerRecyclerViewWithDeadline(@Nullable RecyclerView innerView,
            long deadlineNs) {
        final LayoutPrefetchRegistryImpl innerPrefetchRegistry = innerView.mPrefetchRegistry;
        innerPrefetchRegistry.collectPrefetchPositionsFromView(innerView, true);
     ...
    }

回调到GapWorker的内部类LayoutPrefetchRegistryImplcollectPrefetchPositionsFromView方法

    void collectPrefetchPositionsFromView(RecyclerView view, boolean nested) {
        mCount = 0;
        if (mPrefetchArray != null) {
            Arrays.fill(mPrefetchArray, -1);
        }

        final RecyclerView.LayoutManager layout = view.mLayout;
        if (view.mAdapter != null
                && layout != null
                && layout.isItemPrefetchEnabled()) {
            if (nested) {
                // nested prefetch, only if no adapter updates pending. Note: we don't query
                // view.hasPendingAdapterUpdates(), as first layout may not have occurred
                if (!view.mAdapterHelper.hasPendingUpdates()) {
                    layout.collectInitialPrefetchPositions(view.mAdapter.getItemCount(), this);
                }
            } else {
                //1)、 需要预加载
                if (!view.hasPendingAdapterUpdates()) {
                    layout.collectAdjacentPrefetchPositions(mPrefetchDx, mPrefetchDy,
                            view.mState, this);
                }
            }

            if (mCount > layout.mPrefetchMaxCountObserved) {
                //预加载 mPrefetchMaxCountObserved = 1
                layout.mPrefetchMaxCountObserved = mCount;
                //是否预加载了
                layout.mPrefetchMaxObservedInInitialPrefetch = nested;
                //2)、更新CacheSize的大小
                view.mRecycler.updateViewCacheSize();
            }
        }
    }
  • 1)、步骤设置mCount的值
    我们看LayoutManager实现了LinearLayoutManager的方法collectInitialPrefetchPositions
    public void collectInitialPrefetchPositions(int adapterItemCount,
            LayoutPrefetchRegistry layoutPrefetchRegistry) {
        final boolean fromEnd;
        final int anchorPos;
        if (mPendingSavedState != null && mPendingSavedState.hasValidAnchor()) {
            // use restored state, since it hasn't been resolved yet
            fromEnd = mPendingSavedState.mAnchorLayoutFromEnd;
            anchorPos = mPendingSavedState.mAnchorPosition;
        } else {
            resolveShouldLayoutReverse();
            fromEnd = mShouldReverseLayout;
            if (mPendingScrollPosition == RecyclerView.NO_POSITION) {
                anchorPos = fromEnd ? adapterItemCount - 1 : 0;
            } else {
                anchorPos = mPendingScrollPosition;
            }
        }

        final int direction = fromEnd
                ? LayoutState.ITEM_DIRECTION_HEAD
                : LayoutState.ITEM_DIRECTION_TAIL;
        int targetPos = anchorPos;
        for (int i = 0; i < mInitialPrefetchItemCount; i++) {
            if (targetPos >= 0 && targetPos < adapterItemCount) {
                //预加载时,添加一个item值
                layoutPrefetchRegistry.addPosition(targetPos, 0);
            } else {
                break; // no more to prefetch
            }
            targetPos += direction;
        }
    }

最后会回到GapWorker中执行addPosition方法

    public void addPosition(int layoutPosition, int pixelDistance) {
        if (layoutPosition < 0) {
            throw new IllegalArgumentException("Layout positions must be non-negative");
        }

        if (pixelDistance < 0) {
            throw new IllegalArgumentException("Pixel distance must be non-negative");
        }

        // allocate or expand array as needed, doubling when needed
        final int storagePosition = mCount * 2;
        if (mPrefetchArray == null) {
            mPrefetchArray = new int[4];
            Arrays.fill(mPrefetchArray, -1);
        } else if (storagePosition >= mPrefetchArray.length) {
            final int[] oldArray = mPrefetchArray;
            mPrefetchArray = new int[storagePosition * 2];
            System.arraycopy(oldArray, 0, mPrefetchArray, 0, oldArray.length);
        }

        // add position
        mPrefetchArray[storagePosition] = layoutPosition;
        mPrefetchArray[storagePosition + 1] = pixelDistance;
        // mCount = 1,可以回到 collectPrefetchPositionsFromView方法中再看执行结果
        mCount++;
    }
  • 2)、更新CacheSize的大小
    执行RecyclerViewupdateViewCacheSize方法
    void updateViewCacheSize() {
        int extraCache = mLayout != null ? mLayout.mPrefetchMaxCountObserved : 0;
        //mViewCacheMax = 3
        mViewCacheMax = mRequestedCacheMax + extraCache;

        // first, try the views that can be recycled
        //是否满足向 pool 中加入值
        for (int i = mCachedViews.size() - 1;
             i >= 0 && mCachedViews.size() > mViewCacheMax; i--) {
            //向 pool 中加入VH
            recycleCachedViewAt(i);
        }
    }

二、代码展示

下面是一个简单的代码来讲解预加载的打开或关闭效果

public class CheckCacheSizeActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;

    public static void startCheckCacheSizeActivity(Activity activity) {
        Intent intent = new Intent(activity, CheckCacheSizeActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_cache_size);
        mRecyclerView = findViewById(R.id.cache_rv);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setAdapter(new MyCheckCacheAdapter(initDate()));

        //关闭预加载使能
        layoutManager.setItemPrefetchEnabled(false);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    Class<?> clazz = Class.forName("androidx.recyclerview.widget.LinearLayoutManager");
                    //获取预加载的个数
                    Field mPrefetchMaxCountObserved = clazz.getSuperclass()
                            .getDeclaredField("mPrefetchMaxCountObserved");
                    mPrefetchMaxCountObserved.setAccessible(true);
                    Log.e("--->", "mPrefetchMaxCountObserved = " + mPrefetchMaxCountObserved.get(layoutManager));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    Class<?> clazz = Class.forName("androidx.recyclerview.widget.RecyclerView");
                    Field mRecyclerField = clazz.getDeclaredField("mRecycler");
                    mRecyclerField.setAccessible(true);
                    RecyclerView.Recycler recycler  = (RecyclerView.Recycler) mRecyclerField.get(mRecyclerView);
                    Class<?> recyclerClass = recycler.getClass();
                    //获取缓存 mCachedViews
                    Field mCachedViews = recyclerClass.getDeclaredField("mCachedViews");
                    mCachedViews.setAccessible(true);
                    ArrayList<RecyclerView.ViewHolder> views = (ArrayList<RecyclerView.ViewHolder>) mCachedViews.get(recycler);
                    Log.e("--->", "mCachedViews.size = " + views.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
    
    private List<String> initDate() {
        List<String> list = new ArrayList<>();
        for (int i =0; i < 40; i ++){
            list.add("This is item " + i);
        }
        return list;
    }

    class MyCheckCacheAdapter extends RecyclerView.Adapter<MyCheckCacheAdapter.MyViewHolder> {
        private List<String> mList;

        public MyCheckCacheAdapter(List<String> list) {
            mList = list;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.check_cache_rv_layout, null);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.mTextView.setText(mList.get(position));
        }

        @Override
        public int getItemCount() {
            return mList != null ? mList.size() : 0;
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            private TextView mTextView;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                mTextView = itemView.findViewById(R.id.name_tv);
            }
        }
    }
}

2.1、打开预加载

layoutManager.setItemPrefetchEnabled(true);打开预加载

  • 效果
//预加载个数
 E/--->: mPrefetchMaxCountObserved = 1
//mCachedViews 的大小
 E/--->: mCachedViews.size = 3

2.2、关闭预加载

layoutManager.setItemPrefetchEnabled(false);关闭预加载

  • 效果
E/--->: mPrefetchMaxCountObserved = 0
E/--->: mCachedViews.size = 2

由上面可见 mCachedViews的大小等于 DEFAULT_CACHE_SIZE + mPrefetchMaxCountObserved的大小。

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

推荐阅读更多精彩内容