美文网首页Android知识
RecyclerView使用swapAdapter来切换adap

RecyclerView使用swapAdapter来切换adap

作者: Dragon_Boat | 来源:发表于2017-04-07 14:54 被阅读2247次

小记

我们使用RecyclerView时候,一般是setAdapter一次,之后通过调用adapter.notify()来更新数据和UI(不讨论差量更新)。
最近由于业务需求,出现一个界面中由一个RecyclerView承载所有内容,但是可以通过界面内tab_button来切换内容类别的情况,用于内容数据量较大,希望来回切换能流畅迅速。因此这里我采用了多个adapter来记录不同的类别数据,来回切换只要调用setAdapter(Adapter adapter)即可,实际也如愿完成了功能。
偶然看recyclerView源码中,有这样一个函数:

    /**
     * Swaps the current adapter with the provided one. It is similar to
     * {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same
     * {@link ViewHolder} and does not clear the RecycledViewPool.
     * <p>
     * Note that it still calls onAdapterChanged callbacks.
     *
     * @param adapter The new adapter to set, or null to set no adapter.
     * @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing
     *                                      Views. If adapters have stable ids and/or you want to
     *                                      animate the disappearing views, you may prefer to set
     *                                      this to false.
     * @see #setAdapter(Adapter)
     */
    public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
        // bail out if layout is frozen
        setLayoutFrozen(false);
        setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
        setDataSetChangedAfterLayout();
        requestLayout();
    }

看注释基本就能够明白,这是一个和setAdapter类似的方法,不过,针对于界面view结构类似或者相同,需要频繁设置adapter的时候,做了优化,能够再切换的时候复用相同的viewHolder,减少一定的开销。


  • ToDo: 比较两种方法下,性能提升数据。

相关文章

网友评论

    本文标题:RecyclerView使用swapAdapter来切换adap

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