欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RecyclerView使用onBindViewHolder时,同一个Item总是有两个viewholder对象

程序员文章站 2022-06-02 15:42:38
...

RecyclerView中有两个Api来绑定数据:onBindViewHolder( RecyclerView.ViewHolder holder, int position)和带参数onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads)局部绑定/刷新数据。

场景:RecyclerView使用viewHolder保存数据时,同一个Item总是有两个viewHolder对象。比如保存上一次的下载时间,百分比等
比如需要在viewHolder中保存上次刷新的数据时,同一个item有两个viewHolder对象,肯定时不行的,这时只需要在mRecycler中设置setSupportsChangeAnimations()false即可。

原因: RecyclerView默认情况下会创建ViewHolder的另一个副本,以便将视图相互淡化。

另外,当时用带参数的 onBindViewHolder时,因为旧的ViewHolder获取payloads,但新的ViewHolder没有获取到payloads,也需要配置如下代码。

((SimpleItemAnimator)mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);

RecyclerView源码:ItemAnimator 决定使用同一个ViewHolder 还是重新创建ViewHolder,canReuseUpdatedViewHolder()默认返回为true。若为true,则使用同一个ViewHolder。
SimpleItemAnimator继承RecyclerView,通过setSupportsChangeAnimations(),给全局变量mSupportsChangeAnimations (默认为true)设置为false;那么canReuseUpdatedViewHolder()返回为true。
DefaultItemAnimator继承SimpleItemAnimator:canReuseUpdatedViewHolder()中调用super.canReuseUpdatedViewHolder(viewHolder, payloads);即SimpleItemAnimator中的canReuseUpdatedViewHolder()。

RecyclerView源码:

/**
         * When an item is changed, ItemAnimator can decide whether it wants to re-use
         * the same ViewHolder for animations or RecyclerView should create a copy of the
         * item and ItemAnimator will use both to run the animation (e.g. cross-fade).
         * <p>
         * Note that this method will only be called if the {@link ViewHolder} still has the same
         * type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive
         * both {@link ViewHolder}s in the
         * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method.
         *
         * @param viewHolder The ViewHolder which represents the changed item's old content.
         * @param payloads A non-null list of merged payloads that were sent with change
         *                 notifications. Can be empty if the adapter is invalidated via
         *                 {@link RecyclerView.Adapter#notifyDataSetChanged()}. The same list of
         *                 payloads will be passed into
         *                 {@link RecyclerView.Adapter#onBindViewHolder(ViewHolder, int, List)}
         *                 method <b>if</b> this method returns <code>true</code>.
         *
         * @return True if RecyclerView should just rebind to the same ViewHolder or false if
         *         RecyclerView should create a new ViewHolder and pass this ViewHolder to the
         *         ItemAnimator to animate. Default implementation calls
         *         {@link #canReuseUpdatedViewHolder(ViewHolder)}.
         *
         * @see #canReuseUpdatedViewHolder(ViewHolder)
         */
        public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder,
                @NonNull List<Object> payloads) {
            return canReuseUpdatedViewHolder(viewHolder);
        }


     public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder            viewHolder) {
            return true;
        }

SimpleItemAnimator源码:

boolean mSupportsChangeAnimations = true;

    /**
     * Returns whether this ItemAnimator supports animations of change events.
     *
     * @return true if change animations are supported, false otherwise
     */
    @SuppressWarnings("unused")
    public boolean getSupportsChangeAnimations() {
        return mSupportsChangeAnimations;
    }

    /**
     * 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.
     *
     * @param supportsChangeAnimations true if change animations are supported by
     *                                 this ItemAnimator, false otherwise. If the property is false,
     *                                 the ItemAnimator
     *                                 will not receive a call to
     *                                 {@link #animateChange(ViewHolder, ViewHolder, int, int, int,
     *                                 int)} when changes occur.
     * @see Adapter#notifyItemChanged(int)
     * @see Adapter#notifyItemRangeChanged(int, int)
     */
    public void setSupportsChangeAnimations(boolean supportsChangeAnimations) {
        mSupportsChangeAnimations = supportsChangeAnimations;
    }

    /**
     * {@inheritDoc}
     *
     * @return True if change animations are not supported or the ViewHolder is invalid,
     * false otherwise.
     *
     * @see #setSupportsChangeAnimations(boolean)
     */
    @Override
    public boolean canReuseUpdatedViewHolder(@NonNull RecyclerView.ViewHolder viewHolder) {
        return !mSupportsChangeAnimations || viewHolder.isInvalid();
    }

DefaultItemAnimator源码:

 /**
     * {@inheritDoc}
     * <p>
     * If the payload list is not empty, DefaultItemAnimator returns <code>true</code>.
     * When this is the case:
     * <ul>
     * <li>If you override {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}, both
     * ViewHolder arguments will be the same instance.
     * </li>
     * <li>
     * If you are not overriding {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)},
     * then DefaultItemAnimator will call {@link #animateMove(ViewHolder, int, int, int, int)} and
     * run a move animation instead.
     * </li>
     * </ul>
     */
    @Override
    public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder,
            @NonNull List<Object> payloads) {
        return !payloads.isEmpty() || super.canReuseUpdatedViewHolder(viewHolder, payloads);
    }