RecyclerView对数据源的操作
//刷新所有
public final void notifyDataSetChanged();
//position数据发生了改变,那调用这个方法,就会回调对应position的onBindViewHolder()方法了
public final void notifyItemChanged(int position);
//刷新从positionStart开始itemCount数量的item了(这里的刷新指回调onBindViewHolder()方法)
public final void notifyItemRangeChanged(int positionStart, int itemCount);
//在第position位置被插入了一条数据的时候可以使用这个方法刷新,注意这个方法调用后会有插入的动画,这个动画可以使用默认的,也可以自己定义
public final void notifyItemInserted(int position);
//从fromPosition移动到toPosition为止的时候可以使用这个方法刷新
public final void notifyItemMoved(int fromPosition, int toPosition);
//批量添加
public final void notifyItemRangeInserted(int positionStart, int itemCount);
//第position个被删除的时候刷新,同样会有动画
public final void notifyItemRemoved(int position);
//批量删除
public final void notifyItemRangeRemoved(int positionStart, int itemCount);
问题描述:
RecyclerView中使用notifyItemRangeChanged(int positionStart, int itemCount)时闪屏;
原因
闪烁主要由于RecyclerView使用的默认的动画导致的,所以解决的方法就是修改默认的动画。
解决办法
- 更新部分item
(1)个别更新
imgAdapter.notifyItemChanged(i);// 只更新修改的item
(2)删除某个
selectedImgs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(0,selectedImgs.size());
- 屏蔽动画方法
(1) DefaultItemAnimator继承自SimpleItemAnimator,里面有个方法是:
/**
* Sets whether this ItemAnimator supports animations of item change events.
* If you set this property to false, actions on the data set which change the
* contents of items will not be animated. What those animations do is left
* up to the discretion of the ItemAnimator subclass, in its
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} implementation.
* The value of this property is true by default.
*
*/
public void setSupportsChangeAnimations(boolean supportsChangeAnimations) {
mSupportsChangeAnimations = supportsChangeAnimations;
}
只要设置为false,就可以不显示动画了,也就解决了闪烁问题。 关键代码:
((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
(2)设置动画执行时间为0来解决闪烁问题
recyclerView.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
(3)修改默认的动画
//1.定义动画类
public class NoAlphaItemAnimator extends SimpleItemAnimator {
}
//2.将DefaultItemAnimator类里的代码全部copy到自己写的动画类中,然后做一些修改。
//3.首先找到private void animateChangeImpl(final ChangeInfo changeInfo) {}方法。
//4.找到方法里这两句代码:
//去掉alpha(0)
oldViewAnim.alpha(0).setListener(new VpaListenerAdapter() {...}).start();
oldViewAnim.setListener(new VpaListenerAdapter() {...}).start();
// 去掉alpha(1)
newViewAnimation.translationX(0).translationY(0).setDuration(getChangeDuration()).
alpha(1).setListener(new VpaListenerAdapter() {...}).start();
newViewAnimation.translationX(0).translationY(0).setDuration(getChangeDuration()).
setListener(new VpaListenerAdapter() {...}).start();
//5.最后使用修改后的动画
recyclerView.setItemAnimator(new NoAlphaItemAnimator());