RecyclerView解析--onViewDetachedFromWindow()/onViewAttachedToWindow()


先看這段源碼介紹:

/**
         * Called when a view created by this adapter has been detached from its window.
         *
         * <p>Becoming detached from the window is not necessarily a permanent condition;
         * the consumer of an Adapter's views may choose to cache views offscreen while they
         * are not visible, attaching an detaching them as appropriate.</p>
         *
         * @param holder Holder of the view being detached
         */
        public void onViewDetachedFromWindow(VH holder) {
        }

Called when a view created by this adapter has been detached from its window.
當適配器創建的view(即列表項view)被窗口分離(即滑動離開了當前窗口界面)就會被調用)

 

這個方法就是用來當你的列表項滑出可見窗口之外的時候,需要重寫此方法進行相應的一些操作。

-----------------------------------------------------------------------------------------------------------------

這個方法具體什么時候用呢?

比如:

我有一個列表,列表的每一個列表項里面都要播放一個短視頻,這時候,當我滑動一個列表項直至它消失在可視界面時,便會調用onViewDetachedFromWindow()方法,重要的一點,視頻控件也會執行它自己的onViewDetachedFromWindow()方法,那么此時我再滑動回來,讓該列表項出現在當前界面,會發現視頻那一部分就是黑屏或者白屏了。

注意,出現這個Bug的條件是,該列表項滑動出可視界面,但是滑動距離不長,因為長的話,你再滑回來就會復用View執行onBindViewHolder()方法。

解決方法就是在RecyclerView中重寫onViewDetachedFromWindow()方法,對視頻進行一個相應的操作(初始化等等)。

 

-----------------------------------------------------------------------------------------------------------------

 對應方法:onViewAttachedToWindow() 

 當列表項出現到可視界面的時候調用

/**
         * Called when a view created by this adapter has been attached to a window.
         *
         * <p>This can be used as a reasonable signal that the view is about to be seen
         * by the user. If the adapter previously freed any resources in
         * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
         * those resources should be restored here.</p>
         *
         * @param holder Holder of the view being attached
         */
        public void onViewAttachedToWindow(VH holder) {
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM