0

我在带有 DiffUtil 的 RecyclerView 适配器自定义类中使用了两个 viewType。

在那我更新数据它将更新 Diffutil getChangePayload但它会更新第一个视图类型。

如何将有效负载数据更改为TYPE_ITEM viewType?

> **CustomViewAdapter class**

  private static final int TYPE_HEADER = 0;
  private static final int TYPE_ITEM = 1;

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ITEM) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.home_list_items, parent, false);
                return new MyViewHolder(itemView);
            } else if (viewType == TYPE_HEADER) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.home_banner, parent, false);
                return new HeaderView(itemView);
            }
            return null;
        }



    @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position, @NonNull List<Object> payloads) { 
            Log.d(TAG, "onBindViewHolder: viewholder " + viewHolder);
            Log.d(TAG, "onBindViewHolder: payload " + payloads);
}
4

2 回答 2

1

For your specific case where you have 2 types of items listed below each other (not mixed), I recommend to use the ConcatAdapter from the RecyclerView package:

https://developer.android.com/reference/androidx/recyclerview/widget/ConcatAdapter

It allows you to connect 2 normal ViewAdapters - for each type one separate adapter. This keeps your codebase a lot cleaner and maintainable.

This is a short example how to use it:

 MyAdapter adapter1 = ...;
 AnotherAdapter adapter2 = ...;
 ConcatAdapter concatenated = new ConcatAdapter(adapter1, adapter2);
 recyclerView.setAdapter(concatenated);
于 2021-06-30T07:39:27.310 回答
0
class CustomDiffUtil<T> extends DiffUtil.Callback{

List<T> oldData;
List<T> newData;

public CustomDiffUtil(List<T> oldData,List<T> newData) {
    this.newData = newData;
    this.oldData = oldData;
}

@Override
public int getOldListSize() {
    return oldData.size();
}

@Override
public int getNewListSize() {
    return newData.size();
}

@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
    return oldData.get(oldItemPosition) == newData.get(newItemPosition);
}

@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
    return oldData.get(oldItemPosition).equals(newData.get(newItemPosition));
}

@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
    //you can return particular field for changed item.
    return super.getChangePayload(oldItemPosition, newItemPosition);
}

}

于 2021-06-30T07:33:32.783 回答