Android RecyclerView的notify方法和动画的刷新详解

Posted 路宇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android RecyclerView的notify方法和动画的刷新详解相关的知识,希望对你有一定的参考价值。

前些天发现了一个蛮有意思的人工智能学习网站,8个字形容一下"通俗易懂,风趣幽默",感觉非常有意思,忍不住分享一下给大家。
👉点击跳转到教程

前言:

本篇讲解了RecyclerView关于通知列表刷新的常用的notify方法。和RecyclerView动画的简单详解。

首先看下效果图

1、页面对应的xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="presenter"
            type="com.example.customview.ui.RecyclerViewActivity.Presenter" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".ui.RecyclerViewActivity">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/btn_reset"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="重置"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/btn_refresh_all"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="全部刷新"
                app:layout_constraintStart_toEndOf="@id/btn_reset"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/btn_refresh_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="刷新第2条"
                app:layout_constraintStart_toEndOf="@id/btn_refresh_all"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/btn_refresh_234"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="刷新第2,3,4条"
                app:layout_constraintStart_toEndOf="@id/btn_refresh_2"
                app:layout_constraintTop_toTopOf="parent" />

            <Button
                android:id="@+id/btn_part_refresh_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="局部刷新第2条"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/btn_reset" />

            <Button
                android:id="@+id/btn_part_refresh_234"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="局部刷新第2,3,4条"
                app:layout_constraintStart_toEndOf="@+id/btn_part_refresh_2"
                app:layout_constraintTop_toBottomOf="@id/btn_reset" />

            <Button
                android:id="@+id/btn_insert_1_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="位置1插入一条"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/btn_part_refresh_234" />

            <Button
                android:id="@+id/btn_insert_3_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="位置3插入两条"
                app:layout_constraintStart_toEndOf="@id/btn_insert_1_1"
                app:layout_constraintTop_toBottomOf="@id/btn_part_refresh_234" />

            <Button
                android:id="@+id/btn_move_2_4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="2移到4(都指的是索引)"
                app:layout_constraintStart_toEndOf="@id/btn_insert_3_2"
                app:layout_constraintTop_toBottomOf="@id/btn_part_refresh_234" />

            <Button
                android:id="@+id/btn_remove_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="删除第2条"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/btn_move_2_4" />

            <Button
                android:id="@+id/btn_remove_234"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@(view)->presenter.onClick(view)"
                android:text="删除第2,3,4条"
                app:layout_constraintStart_toEndOf="@id/btn_remove_2"
                app:layout_constraintTop_toBottomOf="@id/btn_move_2_4" />
        </androidx.constraintlayout.widget.ConstraintLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:overScrollMode="never"
            android:scrollbars="none" />
    </LinearLayout>
</layout>

2、对应的适配器代码如下

/**
 * @Author: ly
 * @Date: 2023/3/9
 * @Description: 适配器
 */
public class NotifyDataAdapter extends RecyclerView.Adapter<NotifyDataAdapter.NotifyDataViewHolder> 
    private List<NotifyModel> notifyModels = new ArrayList<>();

    public NotifyDataAdapter(List<NotifyModel> notifyModels) 
        this.notifyModels = notifyModels;
    

    @NonNull
    @Override
    public NotifyDataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        ItemNotifyDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_notify_data, parent, false);
        Log.i("TAG", "onCreateViewHolder: ");
        return new NotifyDataViewHolder(binding);
    

    @Override
    public void onBindViewHolder(@NonNull NotifyDataViewHolder holder, int position) 
        Log.i("TAG", "onBindViewHolder:两个参数 " + position);
        holder.bindData(position);
    


    @Override
    public void onBindViewHolder(@NonNull NotifyDataViewHolder holder, int position, @NonNull List<Object> payloads) 
        Log.i("TAG", "onBindViewHolder:三个参数 " + position);
        if (payloads.isEmpty()) /** payloads为空说明不需要局部刷新,走原有的onBindViewHolder(holder, position) */
            onBindViewHolder(holder, position);
         else 
            for (Object o : payloads) 
                String payload = (String) o;
                if ("title".equals(payload))  /** 只刷新title字段 */
                    holder.binding.tvTitle.setText(notifyModels.get(position).getTitle());
                 else if ("content".equals(payload)) /** 只刷新content字段 */
                    holder.binding.tvContent.setText(notifyModels.get(position).getContent());
                
            
        
    

    @Override
    public int getItemCount() 
        Log.i("TAG", "getItemCount: " + notifyModels.size());
        return notifyModels.size();
    

    @Override
    public int getItemViewType(int position) 
        Log.i("TAG", "getItemViewType: " + position);
        return super.getItemViewType(position);
    

    public class NotifyDataViewHolder extends RecyclerView.ViewHolder 
        ItemNotifyDataBinding binding;

        public NotifyDataViewHolder(@NonNull ItemNotifyDataBinding itemView) 
            super(itemView.getRoot());
            binding = itemView;
        

        public void bindData(int position) 
            binding.setModel(notifyModels.get(position));
        
    

Activity对应的代码如下,关于notify方法已经在注释中给出:

/**
 * @Author: ly
 * @Date: 2023/3/11
 * @Description: RecyclerView常用notify方法
 */
public class RecyclerViewActivity extends AppCompatActivity 
    private ActivityRecyclerViewBinding binding;
    private NotifyDataAdapter adapter;
    private List<NotifyModel> notifyModels = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view);
        binding.setPresenter(new Presenter());
        initData();
//        binding.rvList.setItemAnimator(null);//去掉默认动画
//        binding.rvList.setItemAnimator(new SlideInLeftAnimator());
        binding.rvList.setLayoutManager(new LinearLayoutManager(this));
        adapter = new NotifyDataAdapter(notifyModels);
        binding.rvList.setAdapter(adapter);
    

    private void initData() 
        notifyModels.clear();
        for (int i = 0; i < 5; i++) 
            notifyModels.add(new NotifyModel("第" + i + "个标题", "第" + i + "条详细内容,详细的信息"));
        
    

    public class Presenter 
        public void onClick(View view) 
            if (view == binding.btnReset) 
                reset();
             else if (view == binding.btnRefreshAll) 
                notifyAllData();
             else if (view == binding.btnRefresh2) 
                notify_2();
             else if (view == binding.btnRefresh234) 
                notify_234();
             else if (view == binding.btnPartRefresh2) 
                notifyPart_2();
             else if (view == binding.btnPartRefresh234) 
                notifyPart_234();
             else if (view == binding.btnInsert11) 
                insert_1_1();
             else if (view == binding.btnInsert32) 
                insert_3_2();
             else if (view == binding.btnMove24) 
                move_2_4();
             else if (view == binding.btnRemove2) 
                remove2();
             else if (view == binding.btnRemove234) 
                remove234();
            
        
    

    /**
     * 删除索引为2,3,4条的数据
     */
    private void remove234() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("remove234" + model.getTitle());
            model.setContent("remove234" + model.getContent());
        
        NotifyModel model2 = notifyModels.get(2);
        NotifyModel model3 = notifyModels.get(3);
        NotifyModel model4 = notifyModels.get(4);
        notifyModels.remove(model2);
        notifyModels.remove(model3);
        notifyModels.remove(model4);
        //notifyItemRangeRemoved(int positionStart, int itemCount)
        //从positionStart位置,itemCount数量的数据进行删除
        adapter.notifyItemRangeRemoved(2, 3);
    

    /**
     * 删除索引为2的条目数据
     */
    private void remove2() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("remove2" + model.getTitle());
            model.setContent("remove2" + model.getContent());
        
        notifyModels.remove(2);
        //notifyItemRemoved(int position):列表position位置移除一条数据时调用。
        adapter.notifyItemRemoved(2);
    

    /**
     * 2的位置移动到4
     */
    private void move_2_4() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("move_2_4" + model.getTitle());
            model.setContent("move_2_4" + model.getContent());
        
        //notifyItemMoved(int fromPosition, int toPosition):将条目下标为fromPosition的位置
        //移动到toPosition位置时调用。
        adapter.notifyItemMoved(2, 4);
    

    /**
     * 在索引位置为3的位置,添加了两条数据
     */
    private void insert_3_2() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("insert_3_2" + model.getTitle());
            model.setContent("insert_3_2" + model.getContent());
        
        NotifyModel model = new NotifyModel("insert_3_2 add 3", "insert_3_2 add 3");
        notifyModels.add(3, model);//在索引为3的位置,添加了一条数据
        NotifyModel model1 = new NotifyModel("insert_3_2 add 4", "insert_3_2 add 4");
        notifyModels.add(4, model1);//在索引为3的位置,添加了一条数据
        //notifyItemRangeInserted(int positionStart, int itemCount)
        //从指定的位置开始刷新,添加itemCount个数据
        adapter.notifyItemRangeInserted(3, 2);
    

    /**
     * 索引为1处,插入1条数据
     */
    private void insert_1_1() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("insert_1_1" + model.getTitle());
            model.setContent("insert_1_1" + model.getContent());
        
        NotifyModel model = new NotifyModel("insert_1_1 add", "insert_1_1 add");
        notifyModels.add(1, model);//在索引为1的位置,添加了一条数据
        //notifyItemInserted(position):在position位置添加一条数据
        adapter.notifyItemInserted(1);
    

    /**
     * 局部更新,下标为2开始的三条数据(包含2 那么其实就是2,3,4)
     */
    private void notifyPart_234() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("notifyPart_234" + model.getTitle());
            model.setContent("notifyPart_234" + model.getContent());
        
        NotifyModel model = new NotifyModel("notifyPart_234 add", "notifyPart_234 add");
        notifyModels.add(model);
        // notifyItemRangeChanged(int positionStart, int itemCount,
        //                @Nullable Object payload):从指定的位置开始刷新,指定个item
        //payload用来标记需要局部刷新的部分。
        adapter.notifyItemRangeChanged(2, 3, "content");
    

    /**
     * 局部更新,更新下标索引为2的条目,刷新其中的一个字段
     */
    private void notifyPart_2() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("notifyPart_2" + model.getTitle());
            model.setContent("notifyPart_2" + model.getContent());
        
        NotifyModel model = new NotifyModel("notifyPart_2 add", "notifyPart_2 add");
        notifyModels.add(model);
        //notifyItemChanged(int position, @Nullable Object payload):刷新指定位置
        //payload用来标记需要局部刷新的部分。
        adapter.notifyItemChanged(2, "title");//只局部刷新下标为2的条目数据 数据又新增了一条,这时也会被加载出来。
    

    /**
     * 刷新下标为2开始的三条数据(包含2 那么其实就是2,3,4)
     */
    private void notify_234() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("notify_2" + model.getTitle());
            model.setContent("notify_2" + model.getContent());
        
        NotifyModel model = new NotifyModel("notify_2 add", "notify_2 add");
        notifyModels.add(model);
        //notifyItemRangeChanged(int positionStart, int itemCount):从指定的位置开始刷新,指定个item
        //item传1等价于notifyItemChanged(position)
        adapter.notifyItemRangeChanged(2, 3);
    

    /**
     * 刷新下标位置为2的条目数据
     */
    private void notify_2() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("notify_2" + model.getTitle());
            model.setContent("notify_2" + model.getContent());
        
        NotifyModel model = new NotifyModel("notify_2 add", "notify_2 add");
        notifyModels.add(model);
        //notifyItemChanged(position):刷新指定位置
        adapter.notifyItemChanged(2);//只刷新下标为2的条目数据 数据又新增了一条,这时也会被加载出来。
    

    /**
     * 重置
     */
    private void reset() 
        initData();
        adapter.notifyDataSetChanged();
    

    /**
     * 刷新全部
     */
    public void notifyAllData() 
        for (NotifyModel model : notifyModels) 
            model.setTitle("notifyAll" + model.getTitle());
            model.setContent("notifyAll" + model.getContent());
        
        NotifyModel model = new NotifyModel("notifyAll add", "notifyAll add");
        notifyModels.add(model);
        adapter.notifyDataSetChanged();//刷新全部item
    


下面是调用不同的notify方法适配器执行的方法顺序如下:
对应上文
1、执行notifyAllData(),实际调用的是 notifyDataSetChanged 刷新全部,适配器执行方法如下

getItemCount: 6
getItemCount: 6
getItemCount: 6
getItemViewType: 0
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 1
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 2
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 3
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 4
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 5
onCreateViewHolder: 
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
getItemCount: 6
getItemViewType: 3
getItemCount: 6
getItemViewType: 4
getItemCount: 6
getItemViewType: 5

2、执行notify_2(),实际调用的是 notifyItemChanged(2),适配器执行方法如下

getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
onCreateViewHolder: 
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemViewType: 3
getItemCount: 6
getItemViewType: 4
getItemCount: 6
getItemViewType: 5
onCreateViewHolder: 
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
getItemCount: 6
getItemViewType: 3
getItemCount: 6
getItemViewType: 4
getItemCount: 6
getItemViewType: 5

3、执行notify_234(),实际调用的是 notifyItemRangeChanged(2, 3);,适配器执行方法如下

 getItemCount: 6
 getItemCount: 6
 getItemViewType: 0
 getItemCount: 6
 getItemViewType: 1
 getItemCount: 6
 getItemViewType: 2
 onCreateViewHolder: 
 onBindViewHolder:三个参数
 onBindViewHolder:两个参数
 getItemCount: 6
 getItemViewType: 3
 onCreateViewHolder: 
 onBindViewHolder:三个参数
 onBindViewHolder:两个参数
 getItemCount: 6
 getItemViewType: 4
 onCreateViewHolder: 
 onBindViewHolder:三个参数
 onBindViewHolder:两个参数
 getItemCount: 6
 getItemViewType: 5
 onCreateViewHolder: 
 onBindViewHolder:三个参数
 onBindViewHolder:两个参数
 getItemCount: 6
 getItemCount: 6
 getItemViewType: 0
 getItemCount: 6
 getItemViewType: 1
 getItemCount: 6
 getItemViewType: 2
 getItemCount: 6
 getItemViewType: 3
 getItemCount: 6
 getItemViewType: 4
 getItemCount: 6
 getItemViewType: 5

4、执行notifyPart_2(),实际调用的是 notifyItemChanged(2, “title”);,适配器执行方法如下

getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
onBindViewHolder:三个参数
getItemCount: 6
getItemViewType: 3
getItemCount: 6
getItemViewType: 4
getItemCount: 6
getItemViewType: 5
onCreateViewHolder: 
onBindViewHolder:三个参数
onBindViewHolder:两个参数
getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
getItemCount: 6
getItemViewType: 3
getItemCount: 6
getItemViewType: 4
getItemCount: 6
getItemViewType: 5

5、执行notifyPart_234(),实际调用的是notifyItemRangeChanged(2, 3, “content”);,适配器执行方法如下

getItemCount: 6
getItemCount: 6
getItemViewType: 0
getItemCount: 6
getItemViewType: 1
getItemCount: 6
getItemViewType: 2
onBindViewHolder:

以上是关于Android RecyclerView的notify方法和动画的刷新详解的主要内容,如果未能解决你的问题,请参考以下文章

Android之RecyclerView介绍

Android:RecyclerView里面的RecyclerView,滚动到底部

Android教程2020 - RecyclerView获取滑动距离

Android的import android.support.v7.widget.RecyclerView的RecyclerView标红问题

android之recyclerview的基本使用

android recyclerview怎么设置每次只能滑动一页