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) {
        }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值